Comprehensive Algorithmic Practice Set: Bitwise, Window, Monotonic Stack & Tree Operations
Math & Bit ManipulationModel answerLast 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:
- The sum of the final prices paid for all items.
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Solutions & Algorithmic Analysis
1. Minimum Bitwise Powers of Two Operations
Approach:
We examine the binary representation of $n$. Consecutive runs of 1 bits (e.g., 111 = 7) can either be subtracted one bit at a time (3 operations) or handled by adding $2^i$ to trigger carries (e.g., $7 + 1 = 8 = 2^3$, taking 2 operations total: $+2^0$ and $-2^3$).
Using bitwise greedy strategy:
- If $n \pmod 4 == 3$ (or $n \pmod 2 == 1$ and $(n \gg 1) \pmod 2 == 1$), adding 1 reduces the number of set bits due to carry propagation. An exception occurs when $n = 3$, where $3 - 1 = 2 \implies 1$ step is faster than $3 + 1 = 4 \implies 1$ step (both take 2 total operations, but subtracting avoids carry logic edge cases).
def min_operations_to_zero(n: int) -> int:
ops = 0
while n > 0:
if n % 2 == 0:
n >>= 1
elif n % 4 == 3 and n != 3:
n += 1
ops += 1
else:
n -= 1
ops += 1
return ops
- Time Complexity: $O(\log n)$
- Space Complexity: $O(1)$
2. Minimal Subarray Containing $k$ Unique Elements
Approach: Use the two-pointer / sliding window technique. Expand the right endpoint while tracking element frequencies in a hash map. Once the map size reaches at least $k$, shrink the left endpoint to find the minimal valid subarray length for that right boundary.
def shortest_k_distinct_subarray(nums: list[int], k: int) -> int:
from collections import defaultdict
freq = defaultdict(int)
left = 0
min_len = float('inf')
for right in range(len(nums)):
freq[nums[right]] += 1
while len(freq) >= k:
min_len = min(min_len, right - left + 1)
freq[nums[left]] -= 1
if freq[nums[left]] == 0:
del freq[nums[left]]
left += 1
return min_len if min_len != float('inf') else -1
- Time Complexity: $O(n)$
- Space Complexity: $O(n)$
3. Next Smaller Element Discount
Approach:
Use a monotonic stack storing indices. Iterate through prices. Whenever the current price is less than or equal to the price at the index on top of the stack, pop the stack and apply the discount.
def calculate_discounts(prices: list[int]):
n = len(prices)
final_prices = list(prices)
stack = []
for i in range(n):
while stack and prices[stack[-1]] >= prices[i]:
idx = stack.pop()
final_prices[idx] -= prices[i]
stack.append(i)
return sum(final_prices), sorted(stack)
- Time Complexity: $O(n)$
- Space Complexity: $O(n)$
4. Prime-Step Hop Game
Approach:
Precompute valid primes ending in $3$ up to $n$ using a Sieve of Eratosthenes. Use dynamic programming where dp[i] is the maximum score to reach index $i$. Initialize dp[0] = nums[0] and all other states to $-\infty$.
def max_jump_score(nums: list[int]) -> int:
n = len(nums)
if n == 0: return -1
# Sieve to find primes ending in 3
is_prime = [True] * n
is_prime[0] = is_prime[1] = False
for i in range(2, int(n**0.5) + 1):
if is_prime[i]:
for j in range(i*i, n, i):
is_prime[j] = False
valid_jumps = [1] + [p for p in range(n) if is_prime[p] and p % 10 == 3]
dp = [float('-inf')] * n
dp[0] = nums[0]
for i in range(n):
if dp[i] == float('-inf'): continue
for step in valid_jumps:
if i + step < n:
dp[i + step] = max(dp[i + step], dp[i] + nums[i + step])
return dp[n-1] if dp[n-1] != float('-inf') else -1
- Time Complexity: $O(n \cdot P)$ where $P$ is the count of eligible prime jumps.
- Space Complexity: $O(n)$
5. Anagrammatic Palindromic Ancestor Paths
Approach:
A set of characters can form a palindrome iff at most one character has an odd frequency. Map lowercase characters 'a'-'z' to bit positions $0 \dots 25$. Maintain a running XOR sum of bitmasks from the root down to each node $u$.
The character frequency condition between ancestor $v$ and node $u$ holds if mask[u] ^ mask[parent(v)] has at most 1 set bit (i.e., is 0 or a power of 2). During DFS, maintain a stack of active path bitmasks to answer queries for node $u$ in $O(27)$ time per query.
def count_palindromic_ancestor_paths(n, nodes_chars, parent, queries):
from collections import defaultdict
adj = defaultdict(list)
for child in range(1, n):
adj[parent[child]].append(child)
mask = [0] * n
def dfs(u, cur_mask):
char_bit = 1 << (ord(nodes_chars[u]) - ord('a'))
cur_mask ^= char_bit
mask[u] = cur_mask
for v in adj[u]:
dfs(v, cur_mask)
dfs(0, 0)
# Pre-generate valid XOR differences (0 and single bit powers of 2)
valid_diffs = [0] + [1 << i for i in range(26)]
ans = []
# For each query node, walk up its ancestor chain
for u in queries:
count = 0
curr = u
u_mask = mask[u]
while curr != -1:
# Mask of path u -> v is mask[u] ^ mask[parent[v]]
p_mask = mask[parent[curr]] if parent[curr] != -1 else 0
diff = u_mask ^ p_mask
if diff.bit_count() <= 1:
count += 1
curr = parent[curr]
ans.append(count)
return ans
- Time Complexity: $O(n + q \cdot H)$ where $H$ is tree height (can be optimized with frequency maps to $O(n + q)$).
- Space Complexity: $O(n)$
6. Maximize Pipeline Throughput Under Budget
Approach: Binary search on the answer $T$. For a target $T$, the required cost for node $i$ is $\max(0, T - \text{throughput}[i]) \times \text{scale_cost}[i]$. Check if total required cost $\le \text{budget}$.
def max_throughput(throughput: list[int], scale_cost: list[int], budget: int) -> int:
low = min(throughput)
high = low + budget
def can_achieve(target):
total = 0
for t, c in zip(throughput, scale_cost):
if t < target:
total += (target - t) * c
if total > budget:
return False
return total <= budget
ans = low
while low <= high:
mid = (low + high) // 2
if can_achieve(mid):
ans = mid
low = mid + 1
else:
high = mid - 1
return ans
- Time Complexity: $O(n \log(\text{budget}))$
- Space Complexity: $O(1)$
7. Optimal Elevator Floor Switch
Approach: Iterate over all candidate elevator stopping floors $x \in [0, N]$. For a fixed $x$, initial energy is $E_0 = x \cdot e_1$. Elevator time is $x \cdot t_1$. Then iterate through the remaining $N - x$ stair steps. At step $k$, check if $E > 0$. If valid, accumulate $\lceil c / E \rceil$ time and deduct $e_2$.
import math
def min_travel_time(N: int, e1: int, t1: int, e2: int, c: int) -> int:
min_time = float('inf')
for x in range(N + 1):
E = x * e1
time = x * t1
possible = True
for step in range(N - x):
if E <= 0:
possible = False
break
time += math.ceil(c / E)
E -= e2
if possible:
min_time = min(min_time, time)
return min_time if min_time != float('inf') else -1
- Time Complexity: $O(N^2)$ direct simulation; can be reduced to $O(N)$ with prefix math.
- Space Complexity: $O(1)$
8. Assign Tasks to Two People with Exactly $k$ Tasks for Person A
Approach: Sort tasks by the opportunity cost difference $(A[i] - B[i])$ in descending order. Allocate Person A to the top $k$ tasks with highest relative advantage, and Person B to the remaining $n-k$ tasks.
def max_reward_assignment(A: list[int], B: list[int], k: int) -> int:
diffs = sorted(zip(A, B), key=lambda x: x[0] - x[1], reverse=True)
total = sum(x[0] for x in diffs[:k]) + sum(x[1] for x in diffs[k:])
return total
- Time Complexity: $O(n \log n)$
- Space Complexity: $O(n)$
9. Level Clearance Score From All Starts
Approach: Starting at level $i$, level clearance requires $E \ge \text{layers}[j] + \text{energyReq}[j]$. Thus, from index $i$, we need to find how many consecutive steps $j \ge i$ satisfy the dynamic threshold relative to $K$. Precomputing cumulative layer costs allows binary searching the maximum length reachable from each starting index $i$.
import bisect
def level_scores(layers: list[int], energyReq: list[int], K: int) -> list[int]:
n = len(layers)
pref = [0] * (n + 1)
for i in range(n):
pref[i+1] = pref[i] + layers[i]
scores = [0] * n
for i in range(n):
# We need pref[j+1] - pref[i] <= K - energyReq[j] for each step
# Simulate forward or use segment tree / binary search
cur_E = K
pt = 0
for j in range(i, n):
cur_E -= layers[j]
if cur_E < 0 or cur_E < energyReq[j]:
break
pt += 1
scores[i] = pt
return scores
- Time Complexity: $O(n)$ with monotonic queue/stack optimization; $O(n^2)$ worst-case direct simulation.
- Space Complexity: $O(n)$
10. Buy Maximum Consecutive Items Per Query
Approach:
Use a prefix sum array of prices. For each query (pos, amount), the start position in 0-based indexing is start = pos - 1. Perform binary search (bisect_right) on the prefix sum array to locate the furthest reachable index end such that prefix[end] - prefix[start] <= amount.
import bisect
def max_items_bought(prices: list[int], queries: list[tuple[int, int]]) -> list[int]:
n = len(prices)
pref = [0] * (n + 1)
for i in range(n):
pref[i+1] = pref[i] + prices[i]
results = []
for pos, amount in queries:
start = pos - 1
target = pref[start] + amount
idx = bisect.bisect_right(pref, target) - 1
results.append(idx - start)
return results
- Time Complexity: $O(n + q \log n)$
- Space Complexity: $O(n)$
11. Minimum Edge Reversals so Every Node Can Reach Root
Approach: Use tree re-rooting technique (Tree DP):
- Compute the cost for root
0using standard DFS (dfs1). - Run a second DFS (
dfs2) to transition answer values from parent $u$ to child $v$:- If edge was directed $u \to v$, directing all nodes to $v$ requires reversing $u \to v$ (add 1), while eliminating the need to reverse $v \to u$ (subtract 1 relative to parent's baseline).
- Thus, $\text{ans}[v] = \text{ans}[u] + 1$ if edge is $u \to v$, or $\text{ans}[u] - 1$ if edge is $v \to u$.
def min_reversals_all_roots(n: int, edges: list[list[int]]) -> list[int]:
from collections import defaultdict
adj = defaultdict(list)
for u, v in edges:
adj[u].append((v, 1)) # 1 means forward u -> v
adj[v].append((u, 0)) # 0 means backward u <- v
ans = [0] * n
def dfs1(u, p):
cost = 0
for v, is_forward in adj[u]:
if v != p:
# To bring flow from v to u, a forward edge u->v must be reversed (cost 1)
cost += is_forward + dfs1(v, u)
return cost
ans[0] = dfs1(0, -1)
def dfs2(u, p):
for v, is_forward in adj[u]:
if v != p:
if is_forward == 1:
ans[v] = ans[u] + 1
else:
ans[v] = ans[u] - 1
dfs2(v, u)
dfs2(0, -1)
return ans
- Time Complexity: $O(n)$
- Space Complexity: $O(n)$
12. Sequential Prefix Continuity
Approach:
Maintain running bounding indices $\text{min_pos}$ and $\text{max_pos}$ as we add values $1, 2, \dots, w$.
The set ${1, \dots, w}$ forms a contiguous block in perm if and only if:
$$\text{max_pos} - \text{min_pos} + 1 == w$$
def check_contiguous_prefixes(perm: list[int]) -> list[int]:
n = len(perm)
pos = [0] * (n + 1)
for idx, val in enumerate(perm):
pos[val] = idx
ans = [0] * n
min_pos = float('inf')
max_pos = float('-inf')
for w in range(1, n + 1):
min_pos = min(min_pos, pos[w])
max_pos = max(max_pos, pos[w])
if max_pos - min_pos + 1 == w:
ans[w - 1] = 1
else:
ans[w - 1] = 0
return ans
- Time Complexity: $O(n)$
- Space Complexity: $O(n)$