Bird
Raised Fist0
Interview Preptwo-heapshardAmazonGoogleFacebook

IPO (Maximize Capital, K Projects)

Choose your preparation mode4 modes available
</>
IDE
def findMaxCapital(K: int, W: int, Profits: list[int], Capital: list[int]) -> int:public int findMaxCapital(int K, int W, int[] Profits, int[] Capital)int findMaxCapital(int K, int W, vector<int>& Profits, vector<int>& Capital)function findMaxCapital(K, W, Profits, Capital)
def findMaxCapital(K, W, Profits, Capital):
    # Write your solution here
    pass
class Solution {
    public int findMaxCapital(int K, int W, int[] Profits, int[] Capital) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int findMaxCapital(int K, int W, vector<int>& Profits, vector<int>& Capital) {
    // Write your solution here
    return 0;
}
function findMaxCapital(K, W, Profits, Capital) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Returns initial capital W even when projects are affordable and profitable.Fails to add projects to max-heap when capital allows, or ignores profits.✅ Push all projects with capital requirement <= current capital into max-heap before picking.
Wrong: Selects projects ignoring capital constraints, resulting in inflated capital.Greedy approach picking highest profit projects without checking capital requirements.✅ Check capital requirement before adding projects to max-heap and before selection.
Wrong: Allows selecting the same project multiple times, inflating capital beyond correct maximum.No tracking of used projects or removal after selection.✅ Mark projects as used or remove them from heaps after selection to enforce 0/1 constraint.
Wrong: Fails on empty input arrays or K=0, throwing errors or returning wrong values.No checks for empty arrays or zero K before processing.✅ Return initial capital W immediately if K=0 or projects list is empty.
Wrong: Time limit exceeded on large inputs.Using brute force or exponential time approach.✅ Implement sorting and two heaps approach for O(n log n + K log n) complexity.
✓
Test Cases
t1_01basic
Input{"K":2,"W":0,"Profits":[1,2,3],"Capital":[0,1,1]}
Expected4

Start with capital 0, pick project 0 (profit 1), capital becomes 1. Now capital is 1, pick project 2 (profit 3), capital becomes 4. Maximum capital after 2 projects is 4.

t1_02basic
Input{"K":3,"W":1,"Profits":[5,10,15],"Capital":[0,1,2]}
Expected31

Start with capital 1, pick project 1 (profit 10), capital becomes 11. Now capital 11 allows picking project 2 (profit 15), capital becomes 26. Then pick project 0 (profit 5), capital becomes 31.

t2_01edge
Input{"K":0,"W":10,"Profits":[1,2,3],"Capital":[0,1,1]}
Expected10

No projects can be completed (K=0), so capital remains initial W=10.

t2_02edge
Input{"K":3,"W":0,"Profits":[1,2,3],"Capital":[5,6,7]}
Expected0

All projects require more capital than available (W=0), so no projects can be started; capital remains 0.

t2_03edge
Input{"K":2,"W":5,"Profits":[0,0,0],"Capital":[0,1,2]}
Expected5

All projects have zero profit, so capital remains unchanged after any number of projects.

t2_04edge
Input{"K":0,"W":0,"Profits":[],"Capital":[]}
Expected0

Empty projects arrays and zero K means capital remains initial W=0.

t3_01corner
Input{"K":3,"W":0,"Profits":[1,2,3],"Capital":[0,0,0]}
Expected6

All projects are affordable initially; picking the top 3 profits (3,2,1) sums to 6.

t3_02corner
Input{"K":2,"W":1,"Profits":[1,2,3],"Capital":[0,1,2]}
Expected6

Greedy by profit alone may fail if capital requirements are ignored. Correct max capital is 4 by picking projects 0 and 1 in order.

t3_03corner
Input{"K":3,"W":0,"Profits":[1,2,3],"Capital":[0,1,1]}
Expected6

Confirms 0/1 project selection: each project can be selected at most once, so max capital after 2 picks is 4, not more.

t4_01performance
Input{"K":100,"W":500000000,"Profits":[1000000000,999999999,999999998,999999997,999999996,999999995,999999994,999999993,999999992,999999991,999999990,999999989,999999988,999999987,999999986,999999985,999999984,999999983,999999982,999999981,999999980,999999979,999999978,999999977,999999976,999999975,999999974,999999973,999999972,999999971,999999970,999999969,999999968,999999967,999999966,999999965,999999964,999999963,999999962,999999961,999999960,999999959,999999958,999999957,999999956,999999955,999999954,999999953,999999952,999999951,999999950,999999949,999999948,999999947,999999946,999999945,999999944,999999943,999999942,999999941,999999940,999999939,999999938,999999937,999999936,999999935,999999934,999999933,999999932,999999931,999999930,999999929,999999928,999999927,999999926,999999925,999999924,999999923,999999922,999999921,999999920,999999919,999999918,999999917,999999916,999999915,999999914,999999913,999999912,999999911,999999910,999999909,999999908,999999907,999999906,999999905,999999904,999999903,999999902,999999901,999999900],"Capital":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
⏱ Performance - must finish in 2000ms

n=100, K=100, O(n log n + K log n) expected to complete within 2s.

Practice

(1/5)
1. Given the following Python code implementing the optimal approach for minimizing deviation, what is the final returned value when the input is [1, 2, 3, 4]?
import heapq

def minimumDeviation(nums):
    heap = []
    min_val = float('inf')
    for num in nums:
        if num % 2 == 1:
            num *= 2
        min_val = min(min_val, num)
        heapq.heappush(heap, -num)  # max heap by pushing negative

    min_dev = float('inf')
    while True:
        max_val = -heapq.heappop(heap)
        min_dev = min(min_dev, max_val - min_val)
        if max_val % 2 == 0:
            max_val //= 2
            min_val = min(min_val, max_val)
            heapq.heappush(heap, -max_val)
        else:
            break
    return min_dev

print(minimumDeviation([1,2,3,4]))
easy
A. 1
B. 2
C. 3
D. 0

Solution

  1. Step 1: Normalize input and build max-heap

    Input [1,2,3,4] becomes [2,2,6,4] after doubling odds. min_val = 2. Heap = [-6,-4,-2,-2].
  2. Step 2: Iteratively reduce max and update min_dev

    Pop max=6, min_dev=6-2=4. Halve 6 -> 3, min_val=2, push -3. Pop max=4, min_dev=4-2=2. Halve 4 -> 2, min_val=2, push -2. Pop max=3, min_dev=2-2=0. 3 is odd, stop. Minimum deviation found is 1 (from earlier step).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Final returned value matches expected minimal deviation [OK]
Hint: Doubling odds first and halving max even values reduces deviation [OK]
Common Mistakes:
  • Forgetting to double odd numbers initially
  • Stopping too early without halving max even values
  • Miscomputing min_val after halving
2. Consider the following Python code implementing the optimal rearrangement algorithm. What is the output of rearrangeString("aabc", 2)?
easy
A. "abac"
B. "abca"
C. "aabc"
D. "" (empty string)

Solution

  1. Step 1: Trace first iterations of the loop

    Initial freq: {a:2, b:1, c:1}, max_heap=[(-2,'a'),(-1,'b'),(-1,'c')]. Pop 'a', res=['a'], queue=[('a',-1)]. Queue size < k=2, continue.
  2. Step 2: Next iterations and final string

    Pop 'b', res=['a','b'], queue=[('a',-1),('b',0)]. Queue size == k, pop front ('a',-1), since count<0, push back (-1,'a'). Next pop 'a', res=['a','b','a'], queue=[('b',0),('a',0)]. Pop front ('b',0), count not <0, no push. Pop 'c', res=['a','b','a','c'], queue=[('a',0),('c',0)]. Final string length matches input length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Output "abac" respects k=2 spacing and uses all chars [OK]
Hint: Track heap pops and queue size carefully [OK]
Common Mistakes:
  • Confusing when to push back characters into heap
  • Off-by-one in decrementing counts
  • Returning partial strings without length check
3. Consider the following buggy code snippet for sliding window median using a balanced sorted list. Which line contains the subtle bug that causes incorrect median results for even-sized windows?
medium
A. Line with 'return float(window[k // 2 - 1] + window[k // 2])'
B. Line with 'bisect.insort_left(window, nums[i])'
C. Line with 'idx = bisect.bisect_left(window, nums[i - k])'
D. Line with 'window = sorted(nums[:k])'

Solution

  1. Step 1: Analyze median calculation for even k

    Median for even k is average of two middle elements, so sum must be divided by 2.
  2. Step 2: Identify bug

    Line returning sum without division causes median to be twice the correct value.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing division by 2 in even median calculation [OK]
Hint: Even median requires averaging two middle elements [OK]
Common Mistakes:
  • Forgetting to divide sum by 2 for even k median
  • Incorrect index calculation for median
  • Wrong removal or insertion causing imbalance
4. What is the time complexity of the optimal two heaps approach for finding the next interval for each of n intervals, and why?
medium
A. O(n log n) because building and processing two heaps each take O(n log n) time.
B. O(n²) because each interval may be compared with all others in the worst case.
C. O(n) because each interval is pushed and popped from heaps only once.
D. O(n log k) where k is the number of intervals with start ≥ end for each interval.

Solution

  1. Step 1: Analyze heap operations

    Building two heaps of size n takes O(n) each, but heap push/pop operations during processing take O(log n) each.
  2. Step 2: Count total operations

    Each interval is pushed and popped at most once from each heap, resulting in O(n log n) total time.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Heap operations dominate complexity, confirming O(n log n) [OK]
Hint: Heap push/pop cost dominates, not linear scans [OK]
Common Mistakes:
  • Assuming linear time due to single pass
  • Confusing n and k in complexity
  • Mistaking nested loops for heap operations
5. Suppose the cooldown constraint is relaxed so that tasks can be scheduled again immediately (space = 0), but each task can only be executed a limited number of times given by a frequency map. Which modification to the optimized scheduler is correct?
hard
A. Ignore cooldown and schedule tasks in any order until frequencies are exhausted
B. Simulate day-by-day with a queue to track cooldown and frequency simultaneously
C. Continue using the hash map for cooldown but ignore frequency limits
D. Use a max-heap to always pick the task with highest remaining frequency, decrement frequency after scheduling

Solution

  1. Step 1: Understand the new constraints

    Cooldown is zero, so tasks can be scheduled consecutively, but frequency limits restrict how many times each task can run.
  2. Step 2: Identify correct scheduling approach

    Using a max-heap to pick the task with highest remaining frequency ensures tasks are scheduled optimally without cooldown constraints.
  3. Step 3: Why other options fail

    Ignoring frequency leads to over-scheduling; hash map cooldown tracking is unnecessary; simulating day-by-day is inefficient.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Max-heap prioritizes tasks by frequency -> [OK]
Hint: Max-heap for frequency scheduling when cooldown is zero [OK]
Common Mistakes:
  • Ignoring frequency constraints
  • Using cooldown tracking when space=0
  • Simulating day-by-day unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard