Bird
Raised Fist0
Interview Prepdp-linear-fibonaccimediumAmazonFacebookGoogleBloomberg

Word Break

Choose your preparation mode4 modes available
📋
Problem

Imagine you receive a long string of characters and a dictionary of valid words. You want to know if you can split the string into a sequence of dictionary words, like breaking a secret code into meaningful words.

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Otherwise, return false. Input: string s, list of strings wordDict Output: boolean indicating if s can be segmented

1 ≤ s.length ≤ 10^51 ≤ wordDict.length ≤ 10^41 ≤ wordDict[i].length ≤ 20s and wordDict[i] consist of only lowercase English letters
Edge cases: Empty string s → true (empty string can be segmented trivially)Dictionary contains the entire string as one word → trueString with repeated characters not in dictionary → false
</>
IDE
def wordBreak(s: str, wordDict: list[str]) -> bool:public boolean wordBreak(String s, List<String> wordDict)bool wordBreak(string s, vector<string> wordDict)function wordBreak(s, wordDict)
def wordBreak(s, wordDict):
    # Write your solution here
    pass
class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        // Write your solution here
        return false;
    }
}
#include <vector>
#include <string>
using namespace std;

bool wordBreak(string s, vector<string> wordDict) {
    // Write your solution here
    return false;
}
function wordBreak(s, wordDict) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: falseDP array not initialized with dp[0] = true, so no segmentation possible.✅ Initialize dp[0] = true to represent empty string segmentation.
Wrong: trueGreedy approach accepts partial prefix matches without full segmentation.✅ Check all possible splits j < i, not just longest prefix.
Wrong: falseTreating dictionary words as 0/1 usage, disallowing reuse.✅ Allow dp[i] = true if any dp[j] true and s[j:i] in dictionary, regardless of previous usage.
Wrong: trueFailing to check full string in dictionary as a valid segmentation.✅ Ensure dp[len(s)] updates if s itself is in dictionary.
Wrong: TimeoutNaive recursion or substring extraction causing exponential or cubic time.✅ Use bottom-up DP with efficient substring checks or Trie optimization.
✓
Test Cases
t1_01basic
Input{"s":"leetcode","wordDict":["leet","code"]}
Expectedtrue

The string can be segmented as "leet code" which are both in the dictionary.

t1_02basic
Input{"s":"applepenapple","wordDict":["apple","pen"]}
Expectedtrue

The string can be segmented as "apple pen apple" which are all in the dictionary.

t2_01edge
Input{"s":"","wordDict":["a","b"]}
Expectedtrue

Empty string can be segmented trivially (no words needed).

t2_02edge
Input{"s":"apple","wordDict":["apple"]}
Expectedtrue

The entire string is one dictionary word, so segmentation is true.

t2_03edge
Input{"s":"aaaaaaa","wordDict":["b"]}
Expectedfalse

String contains repeated characters not in dictionary, so segmentation is false.

t3_01corner
Input{"s":"catsandog","wordDict":["cats","dog","sand","and","cat"]}
Expectedfalse

Partial prefixes exist but no full segmentation possible.

t3_02corner
Input{"s":"aaaaaaa","wordDict":["aaaa","aaa"]}
Expectedtrue

Multiple overlapping segmentations possible; must consider all splits.

t3_03corner
Input{"s":"aaaaaaa","wordDict":["a","aa"]}
Expectedtrue

Tests confusion between 0/1 and unbounded usage; words can be reused unlimited times.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 tests O(n^3) brute force time complexity; must complete in 2s using optimized DP.

Practice

(1/5)
1. Given the following code for maxProfit with k=1 and prices = [1, 5, 3], what is the final returned value?
easy
A. 4
B. 5
C. 3
D. 0

Solution

  1. Step 1: Trace buy and sell arrays for each price

    Initialize buy=[-inf,-inf], sell=[0,0]. For price=1: buy[1]=max(-inf,0-1)=-1, sell[1]=0. For price=5: buy[1]=-1, sell[1]=max(0,-1+5)=4. For price=3: buy[1]=-1, sell[1]=max(4,-1+3)=4.
  2. Step 2: Return sell[k]

    sell[1]=4 is the max profit after 1 transaction.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Profit from buying at 1 and selling at 5 is 4 [OK]
Hint: Track buy/sell updates backward for correct profit [OK]
Common Mistakes:
  • Confusing buy and sell updates order
  • Off-by-one in transaction index
2. Given the following code for the Jump Game II problem, what is the value of the variable jumps returned when the input is [2,1,1]?
easy
A. 3
B. 2
C. 1
D. 0

Solution

  1. Step 1: Trace variables for input [2,1,1]

    n=3, loop i in [0,1]. - i=0: furthest = max(0, 0+2) = 2; i == current_end (0), so jumps = 1, current_end = 2 - i=1: furthest = max(2, 1+1) = 2; i != current_end (2), no jump increment Loop ends.
  2. Step 2: Return jumps

    jumps = 1 is returned, meaning minimum 1 jump to reach the end.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    One jump from index 0 to last index covers entire array [OK]
Hint: Increment jumps only when i reaches current_end [OK]
Common Mistakes:
  • Incrementing jumps too early or too late
  • Off-by-one errors in loop range
  • Misunderstanding when to update current_end
3. What is the time complexity of the optimal space-optimized bottom-up dynamic programming solution for the decoding ways problem, and why?
medium
A. O(n) but with O(n) auxiliary space for dp array
B. O(n^2) because each position checks all previous positions
C. O(2^n) due to recursive branching without memoization
D. O(n) because each character is processed once with constant checks

Solution

  1. Step 1: Analyze loop iterations

    The code iterates through the string once, processing each character exactly once.
  2. Step 2: Check operations per iteration

    Each iteration performs constant time checks for single and two-digit validity, no nested loops.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Linear scan with constant work per step -> O(n) time [OK]
Hint: One pass with constant work per character -> O(n) time [OK]
Common Mistakes:
  • Assuming nested loops cause O(n^2)
  • Confusing recursion without memoization complexity
4. Consider the following buggy code for minimum cost climbing stairs. Which line contains the subtle bug that causes incorrect results on some inputs?
medium
A. Line 4: Loop range starting at 2
B. Line 7: Returning prev1 instead of min(prev1, prev2)
C. Line 6: Updating prev2 and prev1
D. Line 3: Initialization of prev2 and prev1

Solution

  1. Step 1: Understand final return logic

    The top can be reached from either last step or second last step, so minimum of prev1 and prev2 must be returned.
  2. Step 2: Identify incorrect return

    Returning only prev1 ignores the possibility that prev2 might be cheaper, causing wrong results.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Return min(prev1, prev2) to cover both possible last steps [OK]
Hint: Return min of last two costs, not just last [OK]
Common Mistakes:
  • Forgetting min at return
  • Misinitializing base cases
  • Incorrect loop boundaries
5. Suppose the cooldown constraint is removed, allowing buying immediately after selling. Which modification to the DP state machine yields the correct optimal profit?
hard
A. Remove the 'cool' state and update 'hold' as max(hold, free - prices[i]) with free = max(free, free)
B. Use a greedy approach buying at every local minimum and selling at every local maximum
C. Keep 'cool' state but allow buying on cooldown day by updating hold = max(hold, cool - prices[i])
D. Remove 'cool' state and update hold = max(hold, free - prices[i]) with free = max(free, free)

Solution

  1. Step 1: Understand cooldown removal effect

    Without cooldown, no need to track cooldown state; buying can happen immediately after selling.
  2. Step 2: Adjust DP states

    Remove 'cool' state; hold updated as max(hold, free - prices[i]); free updated as max(free, free) (effectively unchanged).
  3. Step 3: Why other options fail

    Keeping 'cool' or using greedy breaks correctness or adds unnecessary complexity.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Removing cooldown state matches classic Best Time II problem [OK]
Hint: No cooldown means no cooldown state needed [OK]
Common Mistakes:
  • Trying to keep cooldown state unnecessarily
  • Using greedy which fails on some inputs
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