KatInterview

Comprehensive Algorithmic Practice Set: Bitwise, Window, Monotonic Stack & Tree Operations

Math & Bit ManipulationModel answer
HardModel answerMath & Bit Manipulationbit-manipulationmonotonic-stacktree-dp

Last updated

A practice collection covering essential algorithms: bit manipulation, two pointers, monotonic stack, dynamic programming, binary search, tree path XORs, and graph re-rooting.

This suite contains 12 algorithmic challenges spanning foundational data structures, dynamic programming, tree traversals, and bitwise optimization techniques.


Challenge 1: Minimum Bitwise Powers of Two Operations

Given a positive integer $n$, reduce it to $0$ using the minimum number of steps. In each step, you can perform either $n = n + 2^i$ or $n = n - 2^i$ for any non-negative integer $i \ge 0$.


Challenge 2: Minimal Subarray Containing $k$ Unique Elements

Given an array of integers nums of length $n$ and an integer $k$, find the length of the shortest contiguous subarray that contains at least $k$ distinct values. If no such subarray exists, return -1.


Challenge 3: Next Smaller Element Discount

An online store offers a discount equal to the price of the first item to the right that costs less than or equal to the current item's original price. Given an array prices, output:

  1. The sum of the final prices paid for all items.
  2. The 0-based indices of all items sold at full price (no valid discount found), sorted in ascending order.

Challenge 4: Prime-Step Hop Game

You are navigating an array nums of length $n$ starting at index 0 with the goal of reaching index $n-1$. From index $i$, you can hop to:

  • $i + 1$, or
  • $i + p$, where $p$ is a prime number whose last digit is $3$ (e.g., $3, 13, 23, 43, \dots$), provided $i + p < n$.

Your total score is the sum of array values on all visited indices. Determine the maximum achievable score to reach $n-1$. If index $n-1$ is unreachable, return -1.


Challenge 5: Anagrammatic Palindromic Ancestor Paths

You are given a rooted tree of $n$ nodes indexed $0$ to $n-1$ (with node $0$ as root). Each node contains a single lowercase English character. Given a sequence of query nodes, for each query node $u$, count the number of ancestor endpoints $v$ on the simple path from $u$ up to root $0$ (inclusive of $u$ and $v$) such that the characters on the path $u \to \dots \to v$ can be rearranged to form a palindrome.


Challenge 6: System Throughput Maximization Under Budget

A pipeline consists of $n$ processing nodes. The bottleneck throughput of the system is $T = \min_i \text{throughput}[i]$. You can upgrade node $i$ multiple times; each upgrade adds $1$ to $\text{throughput}[i]$ and costs $\text{scale_cost}[i]$. Given an integer budget, determine the maximum attainable system throughput $T$.


Challenge 7: Optimal Elevator Floor Switch

You are traveling from floor $0$ to floor $N$. You may ride an elevator up to floor $x$ ($0 \le x \le N$).

  • Elevator: Gains $e_1$ energy unit per floor and takes $t_1$ time units per floor.
  • Remaining $N - x$ floors: Must be climbed via stairs.

At the start of stair floor $k$, with energy $E$, climbing takes $\lceil c / E \rceil$ time, after which energy decreases by $e_2$. Energy must satisfy $E > 0$ before starting each stair step. Find the choice of $x$ that minimizes total transit time. Return -1 if no valid $x$ exists.


Challenge 8: Dual Task Allocation with Exact Quota

You have $n$ tasks. Assigning task $i$ to Worker A gives reward $A[i]$, while assigning it to Worker B gives reward $B[i]$. Each task must be assigned to exactly one worker, and Worker A must be assigned exactly $k$ tasks. Find the maximum total reward possible.


Challenge 9: Level Clearance Score From All Starts

You are given level energy requirements layers[0..n-1] and buffer requirements energyReq[0..n-1], alongside initial energy $K$. Starting at index $i$ with energy $E = K$:

  • At level $j \ge i$, pay $E := E - \text{layers}[j]$. If $E < 0$, stop immediately.
  • If $E \ge \text{energyReq}[j]$, pass level $j$ (gain 1 point) and proceed to $j+1$.
  • Otherwise, stop immediately.

Return an array score where score[i] is the total points earned starting from index $i$.


Challenge 10: Range Prefix Budgeting

Given an array prices of size $n$, process $q$ queries. Each query consists of a 1-based index pos and a budget amount. Find the maximum number of consecutive items starting from index pos - 1 that can be purchased without exceeding amount.


Challenge 11: Tree Inversion Toward Root

Given an unrooted tree represented as $n-1$ directed edges $a \to b$, determine for every node $r \in [0, n-1]$ the minimum number of edge reversals required so that all nodes have a valid directed path reaching $r$.


Challenge 12: Sequential Prefix Continuity

Given a permutation perm of integers $1$ through $n$, for each $w \in [1, n]$, determine whether the set of numbers ${1, 2, \dots, w}$ occupies a contiguous sequence of indices in perm. Output a binary array of size $n$ where the $w$-th entry is 1 if true, 0 otherwise.

Hints

Hint 1

For Challenge 1, observe bit patterns: consecutive 1s in binary can be reduced either by clearing them one by one or adding a power of 2 to create a carry.

Hint 2

For Challenge 5, a string can be rearranged into a palindrome if at most one character has an odd frequency. Bitwise XOR masks can track character frequencies efficiently.

Hint 3

For Challenge 11, compute the required reversals for root 0 using standard tree traversal, then update adjacent roots during a secondary re-rooting DFS in O(1) per edge.