PracHub
QuestionsPremiumCoachesLearningGuidesInterview Prep

Quick Overview

This multi-part prompt evaluates algorithmic problem-solving and core data-structure competencies such as array manipulation, modular/date arithmetic, matrix transformations, dynamic set and interval maintenance, string concatenation frequency counting, and path-based expression evaluation on grids.

  • hard
  • Capital One
  • Coding & Algorithms
  • Software Engineer

Solve multiple algorithmic interview questions

Company: Capital One

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Take-home Project

Below are several independent coding tasks. For each task, implement a function that returns the required output. Assume: - Arrays/lists are 0-indexed. - Strings contain ASCII letters/spaces unless stated otherwise. - Aim for efficient time complexity (typically \(O(n\log n)\) or better when possible). --- ## 1) Compare counts above/below a target **Input:** integer `target`, integer array `arr` **Output:** - Return the string: - `"greater"` if `count(x > target)` is larger than `count(x < target)` - `"smaller"` if `count(x < target)` is larger than `count(x > target)` - `"tie"` if they are equal Notes: - Values equal to `target` are ignored. --- ## 2) Moon phase after a given date (8-day cycle) There are 8 moon states in a fixed cycle, labeled `0..7`. The moon advances by 1 state each day (mod 8). **Input:** - `initial_state` (0..7): the moon state on **Jan 1** of a given (non-leap) year - `month` (1..12), `day` (1..31): a calendar date in the same year (assume standard month lengths) **Output:** the moon state (0..7) on the given `month/day`. --- ## 3) Apply commands to a matrix Given an `n x m` integer matrix and a list of string commands, apply them in order and return the final matrix. **Commands:** - `"reverseRow r"`: reverse the elements in row `r` - `"swap r1 r2"`: swap row `r1` and row `r2` - `"rotate"`: rotate the entire matrix **90° clockwise** (dimensions become `m x n`) **Input:** matrix `grid`, list `commands` **Output:** final matrix after all commands. --- ## 4) Longest consecutive sequence length after each insertion Process a list of integers from left to right. After each new number is added to the seen set, output the length of the **longest consecutive-integer sequence** that can be formed from all numbers seen so far. **Input:** integer array `nums` **Output:** integer array `ans` of the same length where `ans[i]` is the longest consecutive length after processing `nums[0..i]`. **Example:** - Input: `[2, 3, 0, 4]` - Output: `[1, 2, 2, 3]` --- ## 5) Count ordered pairs whose concatenation equals target Given an integer array `numbers` and an integer `target`, count the number of **ordered pairs** `(i, j)` with `i != j` such that concatenating their decimal representations equals the target’s decimal representation. Formally, count pairs where: - `str(numbers[i]) + str(numbers[j]) == str(target)` **Input:** `numbers`, `target` **Output:** count of valid ordered pairs. **Example:** - `numbers = [1, 212, 12, 12]`, `target = 1212` - Valid ordered pairs: `(0,1)`, `(2,3)`, `(3,2)` → output `3` --- ## 6) Maximum value of a valid expression along right/down paths in a grid You are given an `n x m` grid of characters. Each cell is either: - a digit `'0'..'9'`, or - an operator `'+'` or `'-'`. You may choose any starting cell and move only **right** or **down** to form a sequence of visited cells (a path). The concatenation of characters along the path must form a **valid expression** under these rules: - A valid expression is either a single digit, or alternates strictly: `digit (op digit)*` - Therefore: - two consecutive digits are invalid - two consecutive operators are invalid The value of an expression is evaluated left-to-right with `+` and `-`. **Task:** Return the maximum value among all valid expressions obtainable from any right/down path in the grid. --- ## 7) Simulate a multi-step array reduction and return the total Given a non-negative integer array `nums`, repeatedly apply the following procedure until all values are `0`: 1. Find the leftmost index `i` such that `nums[i] != 0`. Let `x = nums[i]`. 2. Starting from `i` and moving right, for each `k >= i`: - if `nums[k] >= x`, set `nums[k] = nums[k] - x` and continue - if `nums[k] < x`, stop this pass immediately 3. Add `x` to `ans`. 4. If all elements are now 0, return `ans`; otherwise repeat from step 1. **Input:** `nums` **Output:** the final `ans`. **Example:** - `nums = [3, 5, 5, 1]` → output `6` --- ## 8) Text justification with 2D input (paragraph blocks) You are given a 2D list `blocks`, where each inner list represents a “block” that must start on a **new line**. Each element of a block is a string that may itself contain **multiple words** separated by single spaces. You must produce fully justified lines of width `maxWidth`: - Words cannot be split. - You place words left-to-right into the current line until adding the next word would exceed `maxWidth`, then you start a new line. - If a block contains a string with multiple words, you may split that string into words and continue packing them across lines. - When justifying a line, distribute spaces between words (do **not** insert spaces inside a word). If extra spaces remain, distribute them from left to right. **Input:** `blocks: List[List[str]]`, integer `maxWidth` **Output:** list of justified strings (each exactly length `maxWidth`). --- ## 9) Count symmetric triplets in a string (case-insensitive) Given a string `s`, consider every contiguous substring of length 3 (a “triplet”). A triplet is **symmetric** if its first and third characters are the same, ignoring case. **Input:** string `s` **Output:** number of symmetric triplets. **Examples:** - `"axA"` → `1` ("a x a") - `"cxcbdb"` → `2` --- ## 10) A/P replacement rounds until termination Given an array `arr` containing only characters `'A'` and `'P'`, and an integer `rate` (replacement rate), repeatedly perform **rounds** as follows: In each round: 1. If `arr` ends with at least `rate` consecutive `'P'` characters, remove exactly `rate` trailing `'P'` characters. 2. If `arr` still contains any `'A'`, change the **last** `'A'` in the array to `'P'`. 3. If step (1) cannot remove (not enough trailing `P`) **and** step (2) cannot change (no `A` exists), stop. **Input:** `arr`, integer `rate` **Output:** number of rounds performed until stopping. **Example:** `rate = 3`, `['A','A','P']` evolves: - `['A','A','P']` → `['A','P','P']` → `['P','P','P']` → `[]` So output is `3` rounds. --- ## 11) Minimum value difference with index-distance constraint Given an integer array `nums` and an integer `distance`, find two indices `i, j` such that: - `|i - j| >= distance` Among all such pairs, minimize: - `|nums[i] - nums[j]|` **Input:** `nums`, integer `distance` **Output:** the minimum absolute difference achievable (assume a valid pair exists). --- ## 12) Split array into two groups using “greater-than counts” rule You process array `A` from left to right and assign each element `a` to group `B` or group `C` using this rule: Let: - `gB(a) =` number of elements in `B` strictly greater than `a` - `gC(a) =` number of elements in `C` strictly greater than `a` Assignment: 1. If `gB(a) > gC(a)`, put `a` into `B`. 2. If `gB(a) < gC(a)`, put `a` into `C`. 3. If tied, put `a` into the currently shorter group. 4. If still tied (same length), put `a` into `B`. **Input:** integer array `A` **Output:** the final groups `B` and `C` after processing all elements. **Example:** - Input: `[1,2,3,4,5]` - One valid output: `B = [1,3,5]`, `C = [2,4]` ---

Quick Answer: This multi-part prompt evaluates algorithmic problem-solving and core data-structure competencies such as array manipulation, modular/date arithmetic, matrix transformations, dynamic set and interval maintenance, string concatenation frequency counting, and path-based expression evaluation on grids.

Part 1: Compare counts above and below a target

Given an integer target and an integer array arr, compare how many elements are strictly greater than target versus strictly smaller than target. Ignore elements equal to target. Return 'greater' if the greater-count is larger, 'smaller' if the smaller-count is larger, or 'tie' if they are equal.

Constraints

  • 0 <= len(arr) <= 200000
  • -10^9 <= arr[i], target <= 10^9

Examples

Input: (3, [4, 2, 5, 3, 1])

Expected Output: 'tie'

Explanation: There are two values greater than 3 and two values smaller than 3.

Input: (0, [-1, 1, 2])

Expected Output: 'greater'

Explanation: Two values are greater than 0, while one is smaller.

Input: (5, [1, 2, 3])

Expected Output: 'smaller'

Explanation: All values are smaller than 5.

Input: (7, [])

Expected Output: 'tie'

Explanation: Both counts are zero for an empty array.

Solution

def solution(target, arr):
    greater = sum(1 for x in arr if x > target)
    smaller = sum(1 for x in arr if x < target)
    if greater > smaller:
        return 'greater'
    if smaller > greater:
        return 'smaller'
    return 'tie'

Time complexity: O(n). Space complexity: O(1).

Hints

  1. You only need two counters while scanning the array once.
  2. Elements equal to target should not affect either counter.

Part 2: Moon phase on a given date in an 8-day cycle

There are 8 moon states labeled 0 through 7. The moon advances by 1 state every day modulo 8. Given the state on January 1 of a non-leap year and a date in the same year, compute the moon state on that date.

Constraints

  • 0 <= initial_state <= 7
  • 1 <= month <= 12
  • The date is valid in a non-leap year

Examples

Input: (0, 1, 1)

Expected Output: 0

Explanation: January 1 has the initial state.

Input: (7, 1, 2)

Expected Output: 0

Explanation: One day later, state 7 advances to 0.

Input: (3, 3, 1)

Expected Output: 6

Explanation: 59 days have passed before March 1, so the state is (3 + 59) mod 8 = 6.

Input: (5, 12, 31)

Expected Output: 1

Explanation: December 31 is 364 days after January 1 in a non-leap year.

Solution

def solution(initial_state, month, day):
    month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    offset = sum(month_lengths[:month - 1]) + day - 1
    return (initial_state + offset) % 8

Time complexity: O(1). Space complexity: O(1).

Hints

  1. First compute how many days have passed since January 1.
  2. Use modulo 8 after adding the day offset.

Part 3: Apply row and rotation commands to a matrix

You are given an integer matrix grid and a list of commands. Apply each command in order. Supported commands are reverseRow r to reverse row r, swap r1 r2 to swap two rows, and rotate to rotate the entire matrix 90 degrees clockwise.

Constraints

  • The matrix dimensions are valid for all commands
  • Row indices in commands always refer to the current matrix shape
  • 0 <= total number of cells <= 10^5

Examples

Input: ([[1, 2], [3, 4]], ['reverseRow 0', 'swap 0 1'])

Expected Output: [[3, 4], [2, 1]]

Explanation: Reverse the first row to get [2,1], then swap the two rows.

Input: ([[1, 2, 3], [4, 5, 6]], ['rotate'])

Expected Output: [[4, 1], [5, 2], [6, 3]]

Explanation: A 2x3 matrix becomes a 3x2 matrix after one clockwise rotation.

Input: ([[1, 2], [3, 4], [5, 6]], ['rotate', 'swap 0 1'])

Expected Output: [[6, 4, 2], [5, 3, 1]]

Explanation: Rotate first, then swap the first two rows of the rotated matrix.

Input: ([[7]], ['rotate', 'reverseRow 0'])

Expected Output: [[7]]

Explanation: A 1x1 matrix stays the same.

Solution

def solution(grid, commands):
    grid = [row[:] for row in grid]
    for command in commands:
        parts = command.split()
        if parts[0] == 'reverseRow':
            r = int(parts[1])
            grid[r].reverse()
        elif parts[0] == 'swap':
            r1 = int(parts[1])
            r2 = int(parts[2])
            grid[r1], grid[r2] = grid[r2], grid[r1]
        elif parts[0] == 'rotate':
            if not grid:
                grid = []
            else:
                grid = [list(row) for row in zip(*grid[::-1])]
    return grid

Time complexity: O(total work done by commands). Space complexity: O(number of cells) for rotation output.

Hints

  1. For a clockwise rotation, the new rows come from columns of the old matrix scanned bottom to top.
  2. Remember that rotate changes the number of rows and columns.

Part 4: Longest consecutive-sequence length after each insertion

Process the array from left to right. After each number is seen, consider the set of distinct numbers seen so far and compute the length of the longest consecutive-integer sequence that can be formed. Return that best length after every insertion.

Constraints

  • 0 <= len(nums) <= 200000
  • -10^9 <= nums[i] <= 10^9

Examples

Input: ([2, 3, 0, 4],)

Expected Output: [1, 2, 2, 3]

Explanation: After each insertion, the best sequence lengths are 1, 2, 2, and 3.

Input: ([1, 1, 1],)

Expected Output: [1, 1, 1]

Explanation: Duplicates do not increase the longest consecutive length.

Input: ([],)

Expected Output: []

Explanation: Empty input gives an empty output.

Input: ([100, 4, 200, 1, 3, 2],)

Expected Output: [1, 1, 1, 1, 2, 4]

Explanation: The last insertion connects 1,2,3,4 into a length-4 sequence.

Solution

def solution(nums):
    lengths = {}
    seen = set()
    best = 0
    ans = []

    for x in nums:
        if x not in seen:
            seen.add(x)
            left = lengths.get(x - 1, 0)
            right = lengths.get(x + 1, 0)
            cur = left + 1 + right
            lengths[x] = cur
            lengths[x - left] = cur
            lengths[x + right] = cur
            if cur > best:
                best = cur
        ans.append(best)

    return ans

Time complexity: O(n) average. Space complexity: O(n).

Hints

  1. Duplicate values do not change the seen set.
  2. Store the length of each consecutive interval at its boundaries.

Part 5: Count ordered pairs whose concatenation equals a target

Given a list of non-negative integers numbers and a non-negative integer target, count the ordered pairs of distinct indices (i, j) such that str(numbers[i]) + str(numbers[j]) equals str(target).

Constraints

  • 0 <= len(numbers) <= 200000
  • 0 <= numbers[i], target <= 10^9

Examples

Input: ([1, 212, 12, 12], 1212)

Expected Output: 3

Explanation: Valid ordered pairs are (0,1), (2,3), and (3,2).

Input: ([0, 0], 0)

Expected Output: 0

Explanation: No concatenation of two integer strings can have length 1.

Input: ([12, 1, 21, 121], 121)

Expected Output: 2

Explanation: The valid concatenations are 12+1 and 1+21.

Input: ([11, 11, 1], 1111)

Expected Output: 2

Explanation: The only useful split is 11|11, producing two ordered pairs from the two copies of 11.

Solution

def solution(numbers, target):
    from collections import Counter

    counts = Counter(str(x) for x in numbers)
    t = str(target)
    ans = 0

    for k in range(1, len(t)):
        left = t[:k]
        right = t[k:]
        if left not in counts or right not in counts:
            continue
        if left == right:
            ans += counts[left] * (counts[left] - 1)
        else:
            ans += counts[left] * counts[right]

    return ans

Time complexity: O(n + L). Space complexity: O(n).

Hints

  1. Work with string forms of the numbers.
  2. Try every split of the target string into a prefix and suffix.

Part 6: Maximum value of a valid expression on right/down paths

You are given a rectangular grid of characters, represented as a list of equal-length strings. Each cell contains either a digit 0-9, a plus sign, or a minus sign. You may start at any cell and move only right or down. The visited characters must form a valid expression of the form digit or digit(op digit)*. Evaluate expressions left to right and return the maximum value among all valid paths.

Constraints

  • 1 <= number of rows, columns <= 500
  • The grid contains at least one digit
  • All rows have the same length

Examples

Input: (['1'],)

Expected Output: 1

Explanation: A single digit is already a valid expression.

Input: (['1+2'],)

Expected Output: 3

Explanation: The best valid path is 1+2.

Input: (['1-2', '+3+', '4-5'],)

Expected Output: 9

Explanation: One optimal path is 1 -> + -> 3 -> + -> 5, which evaluates to 9.

Input: (['9-8', '-1+'],)

Expected Output: 9

Explanation: Starting at the digit 9 alone is better than any longer valid expression here.

Solution

def solution(grid):
    if not grid:
        return 0

    n = len(grid)
    m = len(grid[0])
    NEG = -10**18

    digit_dp = [[NEG] * m for _ in range(n)]
    plus_dp = [[NEG] * m for _ in range(n)]
    minus_dp = [[NEG] * m for _ in range(n)]
    best = NEG

    def best_incoming_digit(i, j):
        res = NEG
        if i > 0 and digit_dp[i - 1][j] > res:
            res = digit_dp[i - 1][j]
        if j > 0 and digit_dp[i][j - 1] > res:
            res = digit_dp[i][j - 1]
        return res

    for i in range(n):
        for j in range(m):
            c = grid[i][j]
            if c.isdigit():
                val = ord(c) - ord('0')
                cur = val

                if i > 0:
                    if plus_dp[i - 1][j] != NEG:
                        cur = max(cur, plus_dp[i - 1][j] + val)
                    if minus_dp[i - 1][j] != NEG:
                        cur = max(cur, minus_dp[i - 1][j] - val)
                if j > 0:
                    if plus_dp[i][j - 1] != NEG:
                        cur = max(cur, plus_dp[i][j - 1] + val)
                    if minus_dp[i][j - 1] != NEG:
                        cur = max(cur, minus_dp[i][j - 1] - val)

                digit_dp[i][j] = cur
                if cur > best:
                    best = cur

            elif c == '+':
                incoming = best_incoming_digit(i, j)
                if incoming != NEG:
                    plus_dp[i][j] = incoming
            else:
                incoming = best_incoming_digit(i, j)
                if incoming != NEG:
                    minus_dp[i][j] = incoming

    return best if best != NEG else 0

Time complexity: O(nm). Space complexity: O(nm).

Hints

  1. A valid path must alternate between digit cells and operator cells.
  2. For each cell, track the best complete value if the path ends at a digit, and the best pending value if the path ends at + or -.

Part 7: Simulate the array reduction process and return the total

Given a non-negative integer array nums, repeatedly take the leftmost non-zero value x and subtract x from a contiguous stretch to its right while values stay at least x. Add each chosen x to the answer. Continue until the entire array becomes zero, and return the total.

Constraints

  • 0 <= len(nums) <= 200000
  • 0 <= nums[i] <= 10^9

Examples

Input: ([3, 5, 5, 1],)

Expected Output: 6

Explanation: The passes add 3, then 2, then 1.

Input: ([1, 2, 3],)

Expected Output: 3

Explanation: The total is 1 + 1 + 1.

Input: ([0, 0, 0],)

Expected Output: 0

Explanation: The array is already all zeros.

Input: ([5, 1, 5],)

Expected Output: 10

Explanation: The process contributes 5, then 1, then 4.

Solution

def solution(nums):
    ans = 0
    stack = []

    for x in nums:
        while stack and stack[-1] > x:
            stack.pop()
        prev = stack[-1] if stack else 0
        ans += x - prev
        stack.append(x)

    return ans

Time complexity: O(n). Space complexity: O(n).

Hints

  1. You do not need to simulate every subtraction explicitly.
  2. A monotonic nondecreasing stack can capture how much new contribution each element adds.

Part 8: Full text justification with paragraph blocks

You are given blocks, a 2D list where each inner list is a paragraph block that must begin on a new output line. Each string inside a block may contain multiple space-separated words. Split all such strings into words, pack words greedily into lines of width maxWidth, and fully justify every produced line. If a line has one word, left-align it and pad spaces on the right.

Constraints

  • 1 <= maxWidth <= 100
  • Each individual word length is at most maxWidth
  • Total number of words across all blocks is at most 10^5

Examples

Input: ([["This is", "a test"]], 10)

Expected Output: ["This is a", "test "]

Explanation: The first line gets extra spaces distributed from left to right.

Input: ([["ab cd", "ef"], ["gh"]], 5)

Expected Output: ["ab cd", "ef ", "gh "]

Explanation: The second block must start on a new line.

Input: ([["hello"]], 5)

Expected Output: ["hello"]

Explanation: A single word that already matches the width needs no extra padding.

Input: ([["a b c d"]], 6)

Expected Output: ["a b c", "d "]

Explanation: Three single-letter words fit on the first line, and the last word is padded.

Solution

def solution(blocks, maxWidth):
    def justify(words, total_chars):
        spaces = maxWidth - total_chars
        if len(words) == 1:
            return words[0] + ' ' * spaces

        gaps = len(words) - 1
        base = spaces // gaps
        extra = spaces % gaps
        parts = []

        for i, word in enumerate(words[:-1]):
            parts.append(word)
            parts.append(' ' * (base + (1 if i < extra else 0)))
        parts.append(words[-1])
        return ''.join(parts)

    result = []

    for block in blocks:
        words = []
        for piece in block:
            words.extend(piece.split())

        if not words:
            continue

        current = []
        current_chars = 0

        for word in words:
            if not current:
                current = [word]
                current_chars = len(word)
            elif current_chars + len(current) + len(word) <= maxWidth:
                current.append(word)
                current_chars += len(word)
            else:
                result.append(justify(current, current_chars))
                current = [word]
                current_chars = len(word)

        result.append(justify(current, current_chars))

    return result

Time complexity: O(total characters in all words). Space complexity: O(number of words in the current line, excluding output).

Hints

  1. First flatten each block into a word list by splitting on spaces.
  2. To justify one line, compute total spaces needed, divide them across gaps, and place extra spaces from left to right.

Part 9: Count symmetric triplets in a string

A triplet is any contiguous substring of length 3. Count how many triplets are symmetric, meaning the first and third characters are the same when compared case-insensitively.

Constraints

  • 0 <= len(s) <= 200000
  • s contains ASCII letters and spaces

Examples

Input: ('axA',)

Expected Output: 1

Explanation: The only triplet is symmetric because 'a' and 'A' match ignoring case.

Input: ('cxcbdb',)

Expected Output: 2

Explanation: The symmetric triplets are 'cxc' and 'bdb'.

Input: ('ab',)

Expected Output: 0

Explanation: A string shorter than 3 has no triplets.

Input: ('AaAa',)

Expected Output: 2

Explanation: Both triplets, 'AaA' and 'aAa', are symmetric.

Solution

def solution(s):
    s = s.lower()
    return sum(1 for i in range(len(s) - 2) if s[i] == s[i + 2])

Time complexity: O(n). Space complexity: O(n) due to lowercasing the string.

Hints

  1. Scan every window of length 3 exactly once.
  2. Convert the string to one case first so each comparison is simple.

Part 10: Count A/P replacement rounds until the process stops

You are given an array containing only 'A' and 'P', plus a positive integer rate. In each round, first remove exactly rate trailing 'P' characters if they exist. Then, if any 'A' remains, change the last 'A' to 'P'. If neither action is possible in a round, stop. Return the number of rounds performed.

Constraints

  • 0 <= len(arr) <= 200000
  • 1 <= rate <= 200000
  • arr contains only 'A' and 'P'

Examples

Input: (['A', 'A', 'P'], 3)

Expected Output: 3

Explanation: The array evolves to ['A','P','P'], then ['P','P','P'], then [].

Input: (['P', 'P', 'P', 'P'], 2)

Expected Output: 2

Explanation: Each round removes exactly two trailing P values.

Input: (['A'], 2)

Expected Output: 1

Explanation: The single A becomes P in one round, then the process stops.

Input: ([], 1)

Expected Output: 0

Explanation: Nothing can be removed or changed.

Solution

def solution(arr, rate):
    n = len(arr)
    a_positions = [i for i, ch in enumerate(arr) if ch == 'A']
    rounds = 0

    while True:
        while a_positions and a_positions[-1] >= n:
            a_positions.pop()

        changed = False
        trailing_p = n - a_positions[-1] - 1 if a_positions else n

        if trailing_p >= rate:
            n -= rate
            changed = True
            while a_positions and a_positions[-1] >= n:
                a_positions.pop()

        if a_positions:
            a_positions.pop()
            changed = True

        if not changed:
            break

        rounds += 1

    return rounds

Time complexity: O(n + number of removals). Space complexity: O(number of A values).

Hints

  1. You do not need to rebuild the array every round.
  2. Track the current effective length and the positions of remaining 'A' characters.

Part 11: Minimum value difference with an index-distance constraint

Given an integer array nums and an integer distance, find two distinct indices i and j such that |i - j| >= distance and |nums[i] - nums[j]| is minimized. Return that minimum absolute difference.

Constraints

  • 2 <= len(nums) <= 200000
  • 1 <= distance < len(nums)
  • -10^9 <= nums[i] <= 10^9

Examples

Input: ([1, 3, 6, 10, 15], 2)

Expected Output: 5

Explanation: The best valid pair is nums[0] and nums[2], with difference 5.

Input: ([8, 1, 4, 7], 2)

Expected Output: 1

Explanation: Indices 0 and 3 are far enough apart, and |8 - 7| = 1.

Input: ([5, 5], 1)

Expected Output: 0

Explanation: The only valid pair has equal values.

Input: ([1, 100, 2, 99, 3], 2)

Expected Output: 1

Explanation: Pairs such as (0,2) or (1,3) achieve difference 1.

Solution

def solution(nums, distance):
    from collections import deque

    pairs = sorted((value, idx) for idx, value in enumerate(nums))

    def can(limit):
        min_q = deque()
        max_q = deque()
        left = 0

        for right, (value, idx) in enumerate(pairs):
            while min_q and min_q[-1][1] >= idx:
                min_q.pop()
            min_q.append((right, idx))

            while max_q and max_q[-1][1] <= idx:
                max_q.pop()
            max_q.append((right, idx))

            while value - pairs[left][0] > limit:
                if min_q and min_q[0][0] == left:
                    min_q.popleft()
                if max_q and max_q[0][0] == left:
                    max_q.popleft()
                left += 1

            if right > left:
                min_idx = min_q[0][1]
                max_idx = max_q[0][1]
                if idx - min_idx >= distance or max_idx - idx >= distance:
                    return True

        return False

    low = 0
    high = max(nums) - min(nums)

    while low < high:
        mid = (low + high) // 2
        if can(mid):
            high = mid
        else:
            low = mid + 1

    return low

Time complexity: O(n log n + n log V). Space complexity: O(n).

Hints

  1. Sort by value and think about the smallest allowed value gap.
  2. You can binary search the answer and check feasibility with a sliding window over sorted values.

Part 12: Split an array into two groups using greater-than counts

Process array A from left to right and place each value into group B or group C. For a value a, let gB(a) be the number of elements already in B that are strictly greater than a, and define gC(a) similarly. Put a into B if gB(a) > gC(a), into C if gB(a) < gC(a), otherwise into the shorter group, and if lengths are still tied, into B. Return the final groups as [B, C].

Constraints

  • 0 <= len(A) <= 200000
  • -10^9 <= A[i] <= 10^9

Examples

Input: ([1, 2, 3, 4, 5],)

Expected Output: [[1, 3, 5], [2, 4]]

Explanation: Ties alternate by group length, with B winning exact ties.

Input: ([1, 4, 2, 3],)

Expected Output: [[1], [4, 2, 3]]

Explanation: Values 2 and 3 prefer C because C has more elements greater than them.

Input: ([],)

Expected Output: [[], []]

Explanation: No elements means both groups stay empty.

Input: ([7],)

Expected Output: [[7], []]

Explanation: The first element always goes to B because everything is tied.

Solution

def solution(A):
    if not A:
        return [[], []]

    values = sorted(set(A))
    index = {v: i + 1 for i, v in enumerate(values)}

    class Fenwick:
        def __init__(self, n):
            self.n = n
            self.bit = [0] * (n + 1)

        def add(self, i, delta):
            while i <= self.n:
                self.bit[i] += delta
                i += i & -i

        def query(self, i):
            s = 0
            while i > 0:
                s += self.bit[i]
                i -= i & -i
            return s

    bit_b = Fenwick(len(values))
    bit_c = Fenwick(len(values))
    B, C = [], []

    for a in A:
        idx = index[a]
        greater_b = len(B) - bit_b.query(idx)
        greater_c = len(C) - bit_c.query(idx)

        if greater_b > greater_c:
            B.append(a)
            bit_b.add(idx, 1)
        elif greater_b < greater_c:
            C.append(a)
            bit_c.add(idx, 1)
        else:
            if len(B) <= len(C):
                B.append(a)
                bit_b.add(idx, 1)
            else:
                C.append(a)
                bit_c.add(idx, 1)

    return [B, C]

Time complexity: O(n log n). Space complexity: O(n).

Hints

  1. For each group, you need to know how many existing values are greater than the current one.
  2. Coordinate compression plus two Fenwick trees can maintain those counts efficiently.
Last updated: Apr 19, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,500+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Solve Four Coding Assessment Tasks - Capital One (medium)
  • Write SQL using joins and window functions - Capital One (medium)
  • Review Preprocessing Code and Tests - Capital One (easy)
  • Remove nodes with a given value - Capital One (medium)
  • Place Pieces on a Grid - Capital One (medium)