跳到主要内容
CodeHarbor 徽标 CodeHarbor 北美 OA辅助 · VO辅助 · 面试辅助
首页 / 工程知识库 / OA 笔试真题

Citadel OA 两道真题深度解析:回文周期字符串并查集轨道与 10^9 天跨度扫描线优化

完整拆解 Citadel 量化软件工程 OA 两道高频硬核真题:利用并查集(Union-Find)求回文与周期 k 双重约束下的最少字符修改数,以及用事件排序扫描线在 10^9 日期跨度上求图像滤镜包日折扣的最低总成本。

专题方向:Citadel / Quant SWE · 发布时间: · 预计阅读:10 分钟
KEY TAKEAWAYS · 核心结论速览
  • Citadel OA(通常 60–75 分钟 2 道题)对大输入复杂度与 64 位整数溢出极为严苛,任何依赖日期值域直接开数组的做法都会立刻触发 MLE 或 TLE。
  • 回文 + 周期 k 密码改造的本质是下标等价关系传递闭包——将 (i, n-1-i) 与 (i, i+k) 全部 union 后,每个连通分量只需保留最高频字符,代价为 size - max_freq。
  • 图像滤镜最低成本题必须采用 startDay 加费、endDay + 1 减费的离散事件扫描线,且必须在取模 10^9 + 7 之前用 64 位原始成本与 discountPrice 比较大小。
Citadel OA 回文周期并查集等价类与图像处理扫描线离散化架构图

一、Citadel OA 考核风格与双题通关框架

Citadel(含 Citadel Securities)Software Engineer 与 Quant Developer 在线笔试以思维密度高、隐藏大样本极端边界多著称。近期高频出现的组合是 “代数/图论等价类分组 + 大跨度区间扫描线”,两道题代码量都在 60 行以内,但只要模型选错就会卡死在 60% 通过率。

题目算法内核最优时间复杂度致命失分点
Q1:Palindrome & Periodic Password并查集(DSU)/ 图连通分量众数贪心O(N · α(N))误以为 n 一定是 k 的倍数;只做单轮镜像漏掉传递性合并
Q2:Minimum Image Processing Cost差分事件排序 + 扫描线区间跳跃O(N log N)逐天枚举 1..10^9 超时;在 min(active, discount) 之前提前取模导致大小关系错乱

二、Question 1:回文与周期双重约束密码(Palindrome and Periodic String)

1. 等价类建模推导

给定长度为 n 的字符串 currentPassword 与正整数周期 k(1 <= k <= n),允许修改任意位置的字符,使新字符串同时满足:

  1. 回文约束:对所有 0 <= i < n,有 s[i] == s[n - 1 - i];
  2. 周期 k 约束:对所有 0 <= i < n - k,有 s[i] == s[i + k]。

注意 n 不一定能被 k 整除!当 n % k != 0 时,回文对称关系与周期平移关系会发生交叉耦合,把原本独立的模 k 同余类串联成更大的连通轨道。因此最稳健、零思维负担的写法就是并查集(Disjoint Set Union):

  • 把 0 .. n-1 视为 n 个节点;
  • 遍历 i:执行 union(i, n - 1 - i),若 i + k < n 再执行 union(i, i + k);
  • 最终同一个连通分量(集合)内的所有下标在最终合法字符串中必须填同一个字母。若某集合大小为 sz、内部原有最高频字符出现次数为 max_cnt,则该集合的最少修改次数必为 sz - max_cnt。

2. 生产级 Python 与 C++ 双语实现

from collections import defaultdict


def min_password_modifications(current_password: str, k: int) -> int:
    n = len(current_password)
    if n <= 1:
        return 0

    parent = list(range(n))
    size = [1] * n

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(a: int, b: int) -> None:
        ra, rb = find(a), find(b)
        if ra == rb:
            return
        if size[ra] < size[rb]:
            ra, rb = rb, ra
        parent[rb] = ra
        size[ra] += size[rb]

    for i in range(n):
        union(i, n - 1 - i)
        if i + k < n:
            union(i, i + k)

    groups: dict[int, list[int]] = defaultdict(list)
    for idx, ch in enumerate(current_password):
        r = find(idx)
        if not groups[r]:
            groups[r] = [0] * 26
        groups[r][ord(ch) - ord("a")] += 1

    total_edits = 0
    for r, freq in groups.items():
        total_edits += size[r] - max(freq)
    return total_edits

以 currentPassword = "abzzbz", k = 3 验证:

  • union(0, 5), union(0, 3), union(5, 2) 将 {0, 2, 3, 5} 合并为四元集合,对应字符 ['a', 'z', 'z', 'z'],最高频 'z' 出现 3 次,代价 4 - 3 = 1;
  • union(1, 4) 将 {1, 4} 合并为二元集合,对应 ['b', 'b'],代价 2 - 2 = 0;
  • 合计返回 1,与手工推导完全吻合。

三、Question 2:图像滤镜最低总成本(Minimum Image Processing Cost)

1. 离散化扫描线核心思想

共有 n 张图像,第 i 张图像必须在闭区间 [startDay[i], endDay[i]] 的每一天都接受滤镜处理,单日单独处理成本为 filterCost[i]。系统每天还提供一个全量包日套餐:支付固定价格 discountPrice 即可在当天一次性处理所有活跃图像。求总最低成本并对 10^9 + 7 取模。

每天的决策彼此完全独立:设第 d 天处于活跃期内的图像集合单日成本总和为 S(d),则第 d 天的最优支出必为 min(S(d), discountPrice)。由于 startDay[i], endDay[i] 可高达 10^9,我们不能按天循环,而应利用相邻事件点之间活跃图像集合恒定不变的性质:

  1. 对每张图像生成两个差分事件:在 startDay[i] 处 +filterCost[i],在 endDay[i] + 1 处 -filterCost[i](注意闭区间右端点必须在下一天才失效!);
  2. 将相同日期的差分增量聚合到字典 delta_by_day 中,并将所有关键日期升序排列为 days[0], days[1], ..., days[m-1];
  3. 从左到右遍历 idx = 0 .. m-2:累加 active_cost += delta_by_day[days[idx]],当前恒定区间的持续天数为 span = days[idx + 1] - days[idx],直接累加 span * min(active_cost, discountPrice)。

2. Python 与 C++64 位防溢出实现

from collections import defaultdict
from typing import List

MOD = 10**9 + 7


def min_image_processing_cost(
    start_day: List[int],
    end_day: List[int],
    filter_cost: List[int],
    discount_price: int,
) -> int:
    events: dict[int, int] = defaultdict(int)
    for s, e, c in zip(start_day, end_day, filter_cost):
        events[s] += c
        events[e + 1] -= c

    sorted_days = sorted(events.keys())
    active_cost = 0
    total_ans = 0

    for i in range(len(sorted_days) - 1):
        d = sorted_days[i]
        active_cost += events[d]
        if active_cost > 0:
            span = sorted_days[i + 1] - d
            daily_best = active_cost if active_cost < discount_price else discount_price
            total_ans = (total_ans + (span % MOD) * (daily_best % MOD)) % MOD

    return total_ans

对应的 C++20 考场速写版(严防 int 乘法溢出):

#include <algorithm>
#include <cstdint>
#include <map>
#include <vector>

long long minImageProcessingCost(
    const std::vector<int>& startDay,
    const std::vector<int>& endDay,
    const std::vector<int>& filterCost,
    long long discountPrice
) {
    constexpr long long MOD = 1'000'000'007LL;
    std::map<long long, long long> events;
    for (size_t i = 0; i < startDay.size(); ++i) {
        events[startDay[i]] += filterCost[i];
        events[static_cast<long long>(endDay[i]) + 1] -= filterCost[i];
    }

    long long active = 0;
    long long ans = 0;
    for (auto it = events.begin(); it != events.end(); ++it) {
        active += it->second;
        auto nxt = std::next(it);
        if (nxt != events.end() && active > 0) {
            long long span = (nxt->first - it->first) % MOD;
            long long daily = std::min(active, discountPrice) % MOD;
            ans = (ans + span * daily) % MOD;
        }
    }
    return ans;
}

3. 考场三大高压自检点

  1. 绝不可对 active 取模:假若 active = 10^9 + 8、discountPrice = 500,一旦提前对 active 取模变成 1,就会错误地判定 active < discountPrice!active 必须全程保持未取模的真实 64 位整数。
  2. endDay[i] + 1 防 int32 溢出:在 C++ / Java 中若 endDay[i] == INT_MAX,endDay[i] + 1 会符号溢出变负数,务必先强转为 long long / long 再加 1。
  3. 同一天多个事件合并:用有序 map(或排序后按同一日期先归并增量再结算区间)才能确保 nxt->first - it->first > 0 时当天所有上下线变动已全部生效。

即将面对 Citadel / Quant SWE 或同类 OA / VO 面试?

微信扫码添加顾问或发邮件至 [email protected],快速匹配北美一线工程师提供 1v1 OA辅助 / VO辅助 / 面试辅助支援。

预约辅助排期 →
CodeHarbor OA/VO 辅助顾问微信二维码 微信扫码预约

延伸阅读

VO 现场面经 · Airbnb / SWE Loop

Airbnb SDE 电面与 VO 全流程拆解:配额云存储、重复扣款 Code Review 与多人连续空闲扫描线

完整复盘 Airbnb SDE 从渐进式电面到终面(VO)四场核心硬仗:支持前缀索引与容量配额回收的四层在线存储引擎、修复预订改期先写库后调支付导致并发双扣的 Code Review(乐观锁 + Transactional Outbox)、至少 K 人连续空闲 D 天的区间合并扫描线,以及房源降价/余房订阅版本去重设计。

阅读 →
VO 现场面经 · Anthropic / SWE VO

Anthropic SDE 四轮 VO 全真复盘:采样栈防抖事件流、流式推理 API 架构与分布式发号器

深度还原 Anthropic 高门槛 SDE 全流程面试(HM Code Review + 四轮 Virtual Onsite):详解采样调用栈转生命周期事件流及连续 N 次防抖(Debounce)Follow-up 代码、多租户流式 LLM Inference API(连续批处理与 KV Cache 内存水位调度)、Snowflake 与双 Buffer 分布式 ID 取舍。

阅读 →