Bird
Raised Fist0
Interview Prepsubsets-combinationsmediumAmazonGoogleFacebook

Matchsticks to Square

Choose your preparation mode4 modes available
</>
IDE
def makesquare(matchsticks: List[int]) -> bool:public boolean makesquare(int[] matchsticks)bool makesquare(vector<int>& matchsticks)function makesquare(matchsticks)
def makesquare(matchsticks: List[int]) -> bool:
    # Write your solution here
    pass
class Solution {
    public boolean makesquare(int[] matchsticks) {
        // Write your solution here
        return false;
    }
}
#include <vector>
using namespace std;

bool makesquare(vector<int>& matchsticks) {
    // Write your solution here
    return false;
}
function makesquare(matchsticks) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: trueNot checking if total sum of matchsticks is divisible by 4 before backtracking.✅ Add a guard clause: if sum(matchsticks) % 4 != 0: return False
Wrong: trueGreedy approach assigning largest sticks first without backtracking all possibilities.✅ Implement full backtracking with pruning instead of greedy assignment.
Wrong: trueNot pruning or checking if any stick length exceeds side length before recursion.✅ Check max(matchsticks) <= side length before starting backtracking.
Wrong: trueIncorrect handling of empty input or single-element input, returning true instead of false.✅ Return false if input is empty or length less than 4.
Wrong: TLEUsing pure brute force recursion without pruning or memoization.✅ Add pruning by sorting sticks descending and memoize states using bitmask or DP.
✓
Test Cases
t1_01basic
Input{"matchsticks":[1,1,2,2,2]}
Expectedtrue

You can form a square with side length 2 by using matchsticks (1+1), (2), (2), (2). Total length is 8, so each side must be 2.

t1_02basic
Input{"matchsticks":[3,3,3,3,4]}
Expectedtrue

Sum is 16, divisible by 4, and can form 4 sides of length 4 by using matchsticks (4), (3+1), (3+1), (3+1) or similar combinations.

t2_01edge
Input{"matchsticks":[]}
Expectedfalse

Empty input means no matchsticks to form a square; must return false.

t2_02edge
Input{"matchsticks":[5]}
Expectedfalse

Only one matchstick cannot form a square; must return false.

t2_03edge
Input{"matchsticks":[1,1,1,2]}
Expectedfalse

Sum is 5, not divisible by 4, so cannot form a square.

t2_04edge
Input{"matchsticks":[10,10,10,10]}
Expectedtrue

Exact boundary case: 4 matchsticks all equal length form a perfect square.

t3_01corner
Input{"matchsticks":[2,2,2,2,2,2,2,2]}
Expectedtrue

All matchsticks have the same length 2; can form square with sides 4 (2+2).

t3_02corner
Input{"matchsticks":[1,1,1,1,2,2,2,2]}
Expectedtrue

Sum is 12, sides are 3; must correctly assign smaller and larger sticks to form sides.

t3_03corner
Input{"matchsticks":[1,1,1,1,1,1,1,1,1,1,1,1,1,1,14]}
Expectedfalse

Sum is 28, sides 7; the large 14 stick cannot fit any side, so no square possible.

t4_01performance
Input{"matchsticks":[1,2,3,4,5,6,7,8,9,10,1,2,3,4,5]}
⏱ Performance - must finish in 2000ms

n=15 matchsticks, backtracking with pruning expected to complete within 2s; brute force O(4^n) would TLE.

Practice

(1/5)
1. You are given an array of integers and need to find the number of subsets whose bitwise OR equals the maximum possible OR value among all subsets. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Greedy approach selecting elements with highest bits set first
B. Iterative bitmask enumeration generating all subsets and computing their OR
C. Dynamic programming based on subset sums
D. Sorting the array and using two pointers to find max OR subsets

Solution

  1. Step 1: Understand the problem requires checking all subsets

    Since the maximum bitwise OR depends on any combination of elements, all subsets must be considered.
  2. Step 2: Identify approach that enumerates all subsets efficiently

    Iterative bitmask enumeration systematically generates all subsets and computes their OR, ensuring no subset is missed.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bitmask enumeration covers all subsets -> optimal [OK]
Hint: Bitmask enumeration covers all subsets exhaustively [OK]
Common Mistakes:
  • Assuming greedy selection suffices for max OR
  • Confusing subset sum DP with bitwise OR problem
2. Consider the following Python code for finding the largest divisible subset. What is the final returned list when the input is [1, 2, 3]?
from typing import List

def largestDivisibleSubset(nums: List[int]) -> List[int]:
    if not nums:
        return []
    nums.sort()
    n = len(nums)
    dp = [1] * n
    prev = [-1] * n
    max_index = 0

    for i in range(n):
        for j in range(i - 1, -1, -1):
            if nums[i] % nums[j] == 0:
                if dp[j] + 1 > dp[i]:
                    dp[i] = dp[j] + 1
                    prev[i] = j
            else:
                break
        if dp[i] > dp[max_index]:
            max_index = i

    result = []
    while max_index >= 0:
        result.append(nums[max_index])
        max_index = prev[max_index]
    return result[::-1]

print(largestDivisibleSubset([1, 2, 3]))
easy
A. [1, 2]
B. [1, 3]
C. [1, 2, 3]
D. [2, 3]

Solution

  1. Step 1: Trace dp and prev arrays

    Sorted nums = [1, 2, 3]. For i=1 (2), dp[1]=2, prev[1]=0 since 2 % 1 == 0. For i=2 (3), dp[2]=2, prev[2]=0 since 3 % 1 == 0 but 3 % 2 != 0 (break early).
  2. Step 2: Reconstruct subset from max_index=1 or 2

    dp[1] and dp[2] both 2, max_index updated to 2 last. Reconstruct: nums[2]=3, prev[2]=0 -> nums[0]=1. Result reversed is [1, 3].
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Subset [1,3] is largest divisible subset returned [OK]
Hint: Trace dp and prev arrays carefully [OK]
Common Mistakes:
  • Assuming [1,2,3] all divisible chain without checking divisibility
  • Confusing indices when reconstructing subset
  • Ignoring early break in inner loop
3. Consider the following Python code implementing letter case permutation using backtracking with in-place modification. What is the final output when the input string is "a1b"?
from typing import List

def letterCasePermutation(s: str) -> List[str]:
    res = []
    arr = list(s)
    def backtrack(i: int):
        if i == len(arr):
            res.append(''.join(arr))
            return
        if arr[i].isdigit():
            backtrack(i + 1)
        else:
            arr[i] = arr[i].lower()
            backtrack(i + 1)
            arr[i] = arr[i].upper()
            backtrack(i + 1)
            arr[i] = s[i]  # revert to original
    backtrack(0)
    return res

print(letterCasePermutation("a1b"))
easy
A. ['a1b', 'a1B', 'A1B', 'A1b']
B. ['a1b', 'A1b', 'a1B', 'A1B']
C. ['a1b', 'a1B', 'A1b', 'A1B']
D. ['A1b', 'a1b', 'A1B', 'a1B']

Solution

  1. Step 1: Trace backtrack calls for input "a1b"

    Index 0 is 'a' (letter), toggled to 'a' then 'A'. Index 1 is '1' (digit), skipped. Index 2 is 'b' (letter), toggled to 'b' then 'B'.
  2. Step 2: Collect permutations in order

    Order of appending: 'a1b', 'a1B', 'A1b', 'A1B'.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches expected toggling order [OK]
Hint: Digits skip toggling; letters toggle lower then upper [OK]
Common Mistakes:
  • Swapping order of uppercase/lowercase calls
  • Misplacing digit handling
4. The following backtracking code attempts to generate all subsets of nums. What is the subtle bug causing incorrect output?
medium
A. Using global variable without resetting between calls
B. Not copying the current subset before appending to result causes all subsets to be the same list
C. Base case missing the empty subset
D. Forgetting to pop after including an element causes subsets to accumulate extra elements

Solution

  1. Step 1: Analyze base case append

    The code appends path directly without copying, so all appended references point to the same mutable list.
  2. Step 2: Consequence of mutation

    As recursion unwinds and path changes, all entries in result reflect the final state of path, causing incorrect subsets.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Appending a copy (path[:]) fixes the bug [OK]
Hint: Always append a copy of the current path to result [OK]
Common Mistakes:
  • Forgetting to pop after append
  • Misunderstanding base case inclusion
5. Suppose the problem is modified so that puzzles can have repeated letters and words can be counted multiple times if they match multiple subsets of the puzzle letters. Which modification to the optimal bitmask + trie approach correctly handles this variant?
hard
A. Preprocess puzzles to remove duplicates and apply the original algorithm unchanged.
B. Modify dfs to not require the puzzle's first letter to be present in the word and allow counting multiple matches per word.
C. Enumerate all subsets of puzzle letters including duplicates and sum counts from trie traversal without filtering first letter.
D. Use a multiset trie that stores counts for repeated letters and traverse all subsets including duplicates.

Solution

  1. Step 1: Understand variant requirements

    Repeated letters in puzzles and multiple counting per word require handling multisets, not just sets.
  2. Step 2: Modify data structure and traversal

    A multiset trie that stores counts for repeated letters and traverses all subsets including duplicates correctly counts all matches.
  3. Step 3: Why other options fail

    Ignoring first letter breaks mandatory condition; removing duplicates loses information; naive enumeration is inefficient.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Multiset trie handles repeated letters and multiple counts correctly [OK]
Hint: Multiset trie needed for repeated letters and multiple counts [OK]
Common Mistakes:
  • Ignoring repeated letters
  • Removing duplicates incorrectly
  • Dropping first letter condition
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