20 real Grab interview questions with full model answers — Coding, System design, Technical. Drawn from the same verified bank ChannelPulse drills from (21 Grab questions in total).
21 Grab questions in the bank
3 categories covered
2 roles: Mobile Engineer, Software Engineer
CodingEasyGrabSoftware Engineer
1. Repeated Substring Pattern (LeetCode)
Model answer
The task
Determine whether a string consists of one or more repetitions of a shorter, nonempty substring.
Key idea
The KMP prefix table records the longest proper prefix that is also a suffix for each prefix of the string. If the whole string has a border of length b, then n - b is a candidate repetition length; it works when it divides the string length.
Approach
Return False for an empty string.
Build the KMP prefix table (lps) for the string.
Let period be the string length minus the final prefix-table value.
Return True if the table shows a nonzero border and period divides the string length.
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n = len(s)
if n == 0:
return False
# lps[i] is the longest proper prefix of s[:i + 1]
# that is also a suffix of that substring.
lps = [0] * n
matched = 0
i = 1
while i < n:
if s[i] == s[matched]:
matched += 1
lps[i] = matched
i += 1
elif matched:
# Keep the already-matched prefix where possible.
matched = lps[matched - 1]
else:
i += 1
border_length = lps[-1]
period = n - border_length
return border_length > 0 and n % period == 0
Complexity:
Time: O(n), since the prefix table is built in one pass.
Space: O(n), for the prefix table.
Common follow-ups
Can you solve it with a string-matching trick? Duplicate the string, remove its first and last characters, then check whether the original appears inside.
What if the repeated unit must have a minimum length? Check that the candidate period meets that length.
How would you return the repeated unit? Return s[:period] when the divisibility check succeeds.
CodingEasyGrabSoftware Engineer
2. Two Sum (LeetCode)
Model answer
The task
Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.
Key idea
As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.
Approach
Create a dictionary mapping previously seen values to their indices.
For each element, compute the complement needed to reach the target.
If that complement is in the dictionary, return its stored index and the current index.
Otherwise, store the current value and index, then continue.
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Map each value already visited to its index.
seen = {}
for index, value in enumerate(nums):
complement = target - value
# A match must come from an earlier, distinct element.
if complement in seen:
return [seen[complement], index]
seen[value] = index
# The standard problem guarantees a solution.
raise ValueError("No two elements sum to the target")
Complexity:
Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
Space: O(n), for the dictionary of values seen so far.
Common follow-ups
What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyGrabSoftware Engineer
3. Valid Parentheses (LeetCode)
Model answer
The task
Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.
Key idea
A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.
Approach
Return False if the string has odd length.
Map each closing bracket to its matching opening bracket.
Scan the string from left to right.
Push opening brackets onto the stack.
For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
Return True only if the stack is empty after the scan.
class Solution:
def isValid(self, s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
openings = set(pairs.values())
stack = []
for char in s:
if char in openings:
stack.append(char)
else:
# A closing bracket must match the latest unmatched opening.
if not stack or stack[-1] != pairs.get(char):
return False
stack.pop()
# Unmatched opening brackets make the sequence invalid.
return not stack
Complexity:
Time: O(n), where n is the string length; each character is processed once.
Space: O(n) in the worst case, when all characters are opening brackets.
Common follow-ups
How would you support additional bracket types? Add their matching pairs to the map.
Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingMediumGrabSoftware Engineer
4. Reconstruct a 2-Row Binary Matrix (LeetCode)
Model answer
The task
Build a two-row binary matrix whose row totals are upper and lower, and whose column totals match colsum. Return an empty list if no such matrix exists.
Key idea
A column with sum 2 must contain two ones, while a column with sum 0 must contain two zeros. After placing those, assign each remaining one to a row that still needs it.
Approach
Create two rows filled with zeros.
For every column with sum 2, put a one in both rows and decrease both remaining row totals.
Reject if either remaining total is negative or their sum differs from the number of columns with sum 1.
For each column with sum 1, place its one in a row with the greater remaining total, then decrease that total.
Return the matrix if both remaining totals reach zero; otherwise return an empty list.
from typing import List
class Solution:
def reconstructMatrix(
self, upper: int, lower: int, colsum: List[int]
) -> List[List[int]]:
n = len(colsum)
top = [0] * n
bottom = [0] * n
# A column totaling two must have a one in each row.
for i, total in enumerate(colsum):
if total == 2:
top[i] = bottom[i] = 1
upper -= 1
lower -= 1
# The remaining ones must exactly fill the remaining row totals.
single_columns = sum(total == 1 for total in colsum)
if upper < 0 or lower < 0 or upper + lower != single_columns:
return []
# Assign each single one to a row that still needs one.
for i, total in enumerate(colsum):
if total == 1:
if upper >= lower:
if upper == 0:
return []
top[i] = 1
upper -= 1
else:
if lower == 0:
return []
bottom[i] = 1
lower -= 1
if upper != 0 or lower != 0:
return []
return [top, bottom]
Complexity:
Time: O(n), where n is the number of columns.
Space: O(n) for the returned matrix.
Common follow-ups
Can the matrix be constructed in place? — If the input representation permits it, reuse storage for the output rows.
What if there are more than two rows? — Assign each column’s required ones among rows with remaining capacity, while ensuring totals remain feasible.
How would you verify a proposed matrix? — Check binary entries, row sums, and each column sum in O(n) time.
CodingMediumGrabSoftware Engineer
5. Longest Palindromic Substring (LeetCode)
Model answer
The task
Given a string, return its longest contiguous substring that reads the same forward and backward. If several substrings have the same maximum length, returning any of them is acceptable.
Key idea
Every palindrome has a center: either a character (odd length) or the gap between two characters (even length). Expand outward from each possible center while the characters match, keeping track of the longest range found.
Approach
Initialize the best range to an empty substring.
For each character position, expand from that position to check odd-length palindromes.
Also expand from the gap after that position to check even-length palindromes.
When an expansion finds a longer palindrome, save its start and end indices.
Return the substring covered by the saved range.
class Solution:
def longestPalindrome(self, s: str) -> str:
best_start = 0
best_length = 0
def expand(left: int, right: int) -> None:
nonlocal best_start, best_length
# Keep expanding while the current range is a palindrome.
while left >= 0 and right < len(s) and s[left] == s[right]:
length = right - left + 1
if length > best_length:
best_start = left
best_length = length
left -= 1
right += 1
for center in range(len(s)):
expand(center, center) # Odd-length palindromes
expand(center, center + 1) # Even-length palindromes
return s[best_start:best_start + best_length]
Complexity:
Time: O(n²), since each of the O(n) centers can expand across O(n) characters.
Space: O(1), excluding the returned substring.
Common follow-ups
How can this be made linear time? Use Manacher’s algorithm to reuse information from previously explored centers.
How would you return all longest palindromic substrings? Track every range tied for the maximum length.
What if the input is empty? The method returns an empty string.
How would you count all palindromic substrings? Count each successful expansion instead of only saving the longest range.
CodingMediumGrabSoftware Engineer
6. Daily Temperatures (LeetCode)
Model answer
The task
For each day in a temperature list, find how many days later a warmer temperature first occurs. If no warmer day follows, its answer is zero.
Key idea
Keep a stack of indices whose temperatures are still waiting for a warmer day. Their temperatures are in non-increasing order; when a warmer day arrives, it resolves the waiting indices at the top.
Approach
Create an answer array filled with zeros and an empty stack of indices.
Scan the temperatures from left to right.
While the current temperature is warmer than the temperature at the stack’s top index, pop that index.
Set its answer to the difference between the current index and the popped index.
Push the current index; unresolved indices remain zero.
from typing import List
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
answer = [0] * n
waiting: List[int] = []
for day, temperature in enumerate(temperatures):
# Resolve every earlier day for which today is the first
# warmer day encountered.
while waiting and temperatures[waiting[-1]] < temperature:
earlier_day = waiting.pop()
answer[earlier_day] = day - earlier_day
# This day is now waiting for a warmer temperature.
waiting.append(day)
return answer
Complexity:
Time: O(n), since each index is pushed and popped at most once.
Space: O(n), for the answer array and the stack.
Common follow-ups
How would you handle temperatures arriving as a stream? Keep the unresolved indices and their temperatures in a stack, and emit answers when warmer values arrive; some earlier outputs may remain pending.
What changes if the question asks for the next colder day? Reverse the comparison so an index is resolved by a lower temperature.
Can the stack store temperatures instead of indices? Not for this output, because the index difference is needed to calculate the number of days.
What happens when temperatures are equal? Equal values do not resolve each other; only a strictly warmer temperature does.
CodingMediumGrabSoftware Engineer
7. Minimum Cost For Tickets (LeetCode)
Model answer
The task
Given the days you need to travel and the prices of one-day, seven-day, and thirty-day passes, find the lowest total cost that covers every travel day.
Key idea
Process travel days from earliest to latest. For each day, consider buying each pass and jump to the first travel day it does not cover; dynamic programming records the cheapest cost of reaching each such position.
Approach
Store dp[i] as the minimum cost to cover all travel days before index i.
Initialize dp[0] to zero; all other positions start unreachable.
For each reachable index, try each pass duration and its matching price.
Use binary search to find the first travel day at or after the pass’s expiration.
Update the cost at that position and return the cost for all days.
from bisect import bisect_left
from typing import List
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
n = len(days)
durations = (1, 7, 30)
# dp[i] is the minimum cost to cover days before index i.
dp = [float("inf")] * (n + 1)
dp[0] = 0
for i in range(n):
if dp[i] == float("inf"):
continue
for duration, price in zip(durations, costs):
# A pass bought on days[i] covers through days[i] + duration - 1.
next_index = bisect_left(days, days[i] + duration)
dp[next_index] = min(dp[next_index], dp[i] + price)
return dp[n]
Complexity:
Time: O(n log n), for up to three binary searches per travel day.
Space: O(n), for the dynamic programming array.
Common follow-ups
Can the time be reduced to O(n)? Yes; maintain a moving pointer for each pass duration as the travel days are processed.
What if the pass durations differ? Replace the duration list with the available pass lengths and apply the same transitions.
What if travel days are not sorted? Sort them first, removing duplicates if needed.
What if the calendar is small and fixed? Use day-by-day dynamic programming, carrying the best cost forward on non-travel days.
CodingMediumGrabSoftware Engineer
8. Subarray Sum Equals K (LeetCode)
Model answer
The task
Count the contiguous subarrays whose elements sum to a given target k. The array may contain negative numbers, so subarray sums do not necessarily grow as the subarray gets longer.
Key idea
For each position, let prefix be the sum of all elements seen so far. A subarray ending here sums to k exactly when an earlier prefix sum equals prefix - k. Keep counts of earlier prefix sums in a hash table.
Approach
Start with prefix sum 0 occurring once, representing the empty prefix.
Scan the array and add each value to the running prefix sum.
Add the number of times prefix - k has appeared to the answer.
Record the current prefix sum for future positions.
from collections import defaultdict
from typing import List
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
# Counts of prefix sums seen so far.
prefix_counts = defaultdict(int)
prefix_counts[0] = 1
prefix_sum = 0
subarray_count = 0
for value in nums:
prefix_sum += value
# Each matching earlier prefix identifies one subarray
# ending at the current position.
subarray_count += prefix_counts[prefix_sum - k]
# Record this prefix only after counting, so the match
# refers to an earlier position.
prefix_counts[prefix_sum] += 1
return subarray_count
Complexity: Time: O(n), where n is the number of elements; each element is processed once.
Complexity: Space: O(n) in the worst case, for the distinct prefix sums stored.
Common follow-ups
Why not use a sliding window? Negative values break the monotonic behavior of window sums that sliding-window techniques rely on.
What if all values are nonnegative? A sliding window can be used, though prefix sums still provide a straightforward solution.
Can this count subarrays for many target values? The prefix-frequency scan is target-specific; repeated queries may need a different strategy depending on the input size and query count.
CodingMediumGrabSoftware Engineer
9. Adding Two Negabinary Numbers (LeetCode)
Model answer
The task
Add two binary numbers whose place values are powers of -2. Each number is given as a list of bits, most significant bit first; return their sum in the same format.
Key idea
Add from right to left, carrying into the next position as in ordinary addition. For a position total s, choose the bit with s % 2 and set the carry to -(s // 2), so s = bit - 2 * carry.
Approach
Start at the rightmost bit of each input, with carry zero.
Add available bits and the carry.
Append the total’s parity, then compute the negabinary carry.
Continue until both inputs and the carry are exhausted.
Reverse the result and remove leading zeroes, keeping one zero if the sum is zero.
class Solution:
def addNegabinary(self, arr1: list[int], arr2: list[int]) -> list[int]:
i, j = len(arr1) - 1, len(arr2) - 1
carry = 0
reversed_result = []
while i >= 0 or j >= 0 or carry:
total = carry
if i >= 0:
total += arr1[i]
i -= 1
if j >= 0:
total += arr2[j]
j -= 1
bit = total % 2
carry = -(total // 2)
reversed_result.append(bit)
result = reversed_result[::-1]
# Remove leading zeroes while leaving one bit for the value zero.
first_nonzero = 0
while first_nonzero < len(result) - 1 and result[first_nonzero] == 0:
first_nonzero += 1
return result[first_nonzero:]
Complexity:
Time: O(max(m, n)), where m and n are the input lengths.
Space: O(max(m, n)) for the result.
Common follow-ups
What if the bits were least significant first? Skip reversing the inputs and result.
How would you subtract two values? Implement negation in base -2, then reuse addition.
Can the output be streamed? Emit bits as they are computed, noting they arrive least significant first.
What edge cases matter? Inputs with different lengths, a carry after the last input bit, and an all-zero result.
CodingMediumGrabSoftware Engineer
10. Jump Game II (LeetCode)
Model answer
The task
Given an array where each value is the maximum distance you can jump forward from that position, find the fewest jumps needed to reach the final index.
Key idea
Treat all indices reachable with the same number of jumps as a layer. While scanning a layer, track the farthest index the next jump can reach; when the current layer ends, commit one jump and move to the next layer.
Approach
If the array has at most one element, return 0.
Track the current layer’s end and the farthest index reachable while scanning it.
When the scan reaches the layer’s end, increment the jump count and set the next layer’s end to the farthest reach.
Stop once the final index is reachable. Return -1 if progress stalls and the end cannot be reached.
from typing import List
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
if n <= 1:
return 0
jumps = 0
layer_end = 0
farthest = 0
# The final index needs no further scan: reaching it is sufficient.
for i in range(n - 1):
farthest = max(farthest, i + nums[i])
if i == layer_end:
# Finish this layer and take one jump into the next.
if farthest == layer_end:
return -1 # Unreachable input.
jumps += 1
layer_end = farthest
if layer_end >= n - 1:
return jumps
return -1
Complexity:
Time: O(n), because each index is scanned once.
Space: O(1), because only a few counters are stored.
Common follow-ups
Return the actual jump path? Store a predecessor when extending the farthest reach, then backtrack from the final index.
What if some indices are unreachable? The implementation returns -1 if the scan cannot extend its reachable range.
Can the same method count jumps to any target index? Yes; treat that target as the end and stop when its layer becomes reachable.
CodingMediumGrabSoftware Engineer
11. Minimum Number of Food Buckets to Feed the Hamsters (LeetCode)
Model answer
The task
Given a row of hamsters (H) and empty spaces (.), place the fewest buckets on empty spaces so every hamster has a bucket immediately to its left or right. Return -1 if that cannot be done.
Key idea
Scan from left to right, handling each hamster that is not already fed by a bucket on its left. Place a bucket to its right when possible: it feeds the current hamster and may also feed the next one.
Approach
Copy the string into a mutable list so bucket placements can be marked.
For each hamster, skip it if the previous position contains a bucket.
Otherwise, place a bucket on the right if that position is empty.
If not, place one on the left if possible; if neither side is empty, return -1.
Return the number of buckets placed.
class Solution:
def minimumBuckets(self, hamsters: str) -> int:
row = list(hamsters)
count = 0
for i, cell in enumerate(row):
if cell != "H":
continue
# A bucket placed earlier already feeds this hamster.
if i > 0 and row[i - 1] == "B":
continue
# Prefer the right: this bucket may also feed the next hamster.
if i + 1 < len(row) and row[i + 1] == ".":
row[i + 1] = "B"
count += 1
elif i > 0 and row[i - 1] == ".":
row[i - 1] = "B"
count += 1
else:
return -1
return count
Complexity:
Time: O(n), where n is the length of the row.
Space: O(n), for the mutable copy used to mark buckets.
Common follow-ups
Return bucket positions too: collect each chosen index when placing a bucket.
Handle a circular row: account for adjacency between the first and last positions.
Minimize bucket cost when positions have different prices: use dynamic programming rather than this greedy choice.
Test impossible layouts: a hamster with no adjacent empty space cannot be fed.
CodingMediumGrabSoftware Engineer
12. Coin Change (LeetCode)
Model answer
The task
Given coin denominations that can be used any number of times, find the fewest coins needed to make the target amount. Return -1 if no combination can make it.
Key idea
Let dp[x] be the minimum number of coins needed to form amount x. For each coin, update larger amounts in ascending order so that the same coin can be reused.
Approach
Initialize all states as unreachable, except dp[0] = 0.
Process each coin denomination.
For each amount from that coin through the target, use the coin if the preceding amount is reachable.
Return the target state, or -1 if it remains unreachable.
from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# amount + 1 is larger than any possible answer using positive coins.
unreachable = amount + 1
dp = [unreachable] * (amount + 1)
dp[0] = 0
# Ascending amounts allow each denomination to be used repeatedly.
for coin in coins:
for current in range(coin, amount + 1):
if dp[current - coin] != unreachable:
dp[current] = min(
dp[current],
dp[current - coin] + 1,
)
return dp[amount] if dp[amount] != unreachable else -1
Complexity:
Time: O(n × amount), where n is the number of denominations.
Space: O(amount) for the dynamic programming array.
Common follow-ups
How can the actual coins be returned? Store the last coin used whenever a state improves, then backtrack from the target.
Could breadth-first search solve it? Yes; treat each amount as a node and each coin as an edge, and find the shortest path from zero to the target.
What changes if each coin has a limited supply? Track the remaining inventory or use a bounded-knapsack method instead of the unlimited reuse update.
CodingMediumGrabSoftware Engineer
13. Accounts Merge (LeetCode)
Model answer
The task
Combine accounts that belong to the same person when they share an email address. Return each merged account with its name and unique email addresses in sorted order.
Key idea
Treat each email as a node. Emails appearing in the same account are connected, and connected components represent merged accounts. Union-Find efficiently builds those components as accounts are processed.
Approach
Create a Union-Find set for each distinct email, and remember the account name associated with each email.
For each account, union its first email with every other email in that account.
Group emails by their final Union-Find root.
Sort each group’s emails and assemble the results.
Sort the result groups for deterministic output.
from typing import List
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
parent: dict[str, str] = {}
rank: dict[str, int] = {}
name_by_email: dict[str, str] = {}
def add(email: str, name: str) -> None:
if email not in parent:
parent[email] = email
rank[email] = 0
name_by_email[email] = name
def find(email: str) -> str:
# Path compression keeps future lookups efficient.
if parent[email] != email:
parent[email] = find(parent[email])
return parent[email]
def union(first: str, second: str) -> None:
root_first = find(first)
root_second = find(second)
if root_first == root_second:
return
# Union by rank keeps the sets shallow.
if rank[root_first] < rank[root_second]:
root_first, root_second = root_second, root_first
parent[root_second] = root_first
if rank[root_first] == rank[root_second]:
rank[root_first] += 1
for account in accounts:
name = account[0]
emails = account[1:]
for email in emails:
add(email, name)
# All emails in this account belong to the same component.
for email in emails[1:]:
union(emails[0], email)
emails_by_root: dict[str, List[str]] = {}
for email in parent:
root = find(email)
emails_by_root.setdefault(root, []).append(email)
merged = []
for emails in emails_by_root.values():
emails.sort()
merged.append([name_by_email[emails[0]], *emails])
# The outer result order is not essential, but sorting makes it stable.
merged.sort()
return merged
Complexity:
Time: O(E α(E) + E log E), where E is the number of distinct emails; sorting dominates.
Space: O(E) for the Union-Find structure and grouped output.
Common follow-ups
Could DFS solve this instead? Yes; build an email graph and find its connected components.
What if two unrelated people have the same name? They remain separate unless their accounts share an email.
How would you handle very large datasets? Partition by email or use distributed connected-components processing, then combine components that cross partitions.
CodingMediumGrabSoftware Engineer
14. House Robber (LeetCode)
Model answer
The task
Given a row of houses with a nonnegative amount of money in each, choose houses to rob so that no two neighboring houses are chosen. Return the largest total amount.
Key idea
For each house, the best total either skips it or robs it and adds its value to the best total two houses earlier. Keep only the previous two best totals, since earlier results are no longer needed.
Approach
Set the best totals for the first two positions to zero.
Scan the house values from left to right.
For each value, compare the best total from skipping this house with the total from robbing it.
Advance the two rolling totals and return the best total after the final house.
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
# best_two_back and best_one_back hold the optimal totals
# for the prefixes ending two and one positions earlier.
best_two_back = 0
best_one_back = 0
for amount in nums:
# Either skip this house, or rob it and add the best
# total that cannot include its immediate neighbor.
current = max(best_one_back, best_two_back + amount)
best_two_back = best_one_back
best_one_back = current
return best_one_back
Complexity:
Time: O(n), where n is the number of houses scanned once.
Space: O(1), using two rolling totals rather than a table.
Common follow-ups
What if the houses are arranged in a circle? Solve two linear ranges: exclude the first house or exclude the last, then take the larger result.
How would you return which houses were robbed? Store the best total for each prefix, then backtrack the choices.
What if some house values are negative? The recurrence still works when robbing no houses is allowed; it will never choose a negative-value house.
CodingMediumGrabSoftware Engineer
15. Number of Steps to Reduce a Number in Binary Representation to One (LeetCode)
Model answer
The task
Given a number as a binary string, count the operations needed to reduce it to one. An even value is halved; an odd value is increased by one.
Key idea
Avoid converting the string to an integer, which may be too large. Scan from the least significant bit toward the leading 1, tracking whether an increment has carried into the current bit.
Approach
Start with zero operations and no carry.
Visit each bit except the leading bit, moving right to left.
Add the carry to the current bit to determine its effective value.
If it is odd (1), incrementing and then halving takes two operations; keep the carry.
Otherwise, halving takes one operation.
Add one final operation if a carry remains at the leading bit.
class Solution:
def numSteps(self, s: str) -> int:
steps = 0
carry = 0
# The leading 1 is handled by the final carry check.
for i in range(len(s) - 1, 0, -1):
bit_with_carry = int(s[i]) + carry
if bit_with_carry == 1:
# Odd: increment, then divide by two.
steps += 2
carry = 1
else:
# Even: divide by two.
steps += 1
return steps + carry
Complexity:
Time: O(n), where n is the length of the binary string.
Space: O(1), using only a few variables.
Common follow-ups
What if the string has leading zeros? Strip them first, while treating an all-zero input according to the desired input rules.
Why not parse the string as an integer? The value may exceed the range supported by fixed-width integer types.
Can this be processed as a stream? Yes; retain the relevant carry state while processing bits from least significant to most significant.
CodingMediumGrabSoftware Engineer
16. Simplify Path (LeetCode)
Model answer
The task
Given an absolute Unix-style path, return its canonical form by removing redundant separators and current-directory components, and resolving parent-directory components.
Key idea
Process the path one component at a time with a stack. Keep ordinary directory names, ignore . and empty components, and pop a directory for .. when possible.
Approach
Split the path on /.
Ignore empty components and ..
For .., pop the most recent directory if the stack is not empty.
Push all other components.
Join the stack with / and add the leading slash. An empty stack represents the root.
class Solution:
def simplifyPath(self, path: str) -> str:
directories = []
for component in path.split("/"):
if component == "" or component == ".":
continue
if component == "..":
if directories:
directories.pop()
else:
directories.append(component)
return "/" + "/".join(directories)
Complexity:
Time: O(n), where n is the length of the path; each character is processed a constant number of times.
Space: O(n), for the components stored in the stack.
Common follow-ups
How would you handle relative paths? Preserve leading .. components that cannot be resolved.
What if directory names can contain escaped slashes? Tokenize according to the specified escaping rules before applying the stack logic.
Can the result be built without storing all components? Not generally with a single forward pass, since parent components may remove earlier names.
CodingMediumGrabSoftware Engineer
17. Group Anagrams (LeetCode)
Model answer
The task
Partition the input strings into groups so that strings in the same group contain the same characters with the same frequencies. The order of the groups does not matter.
Key idea
Sort the characters of each string to create a canonical key. Anagrams produce the same key, so a hash table can collect them together.
Approach
Create a mapping from canonical keys to lists of original strings.
For each string, sort its characters and use the result as its key.
Append the string to the list for that key.
Return all grouped lists.
from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for word in strs:
# Anagrams have identical sorted-character representations.
key = "".join(sorted(word))
groups[key].append(word)
return list(groups.values())
Complexity:
Time: O(n · k log k), where n is the number of strings and k is the maximum string length.
Space: O(n · k) to store the grouped strings and their keys.
Common follow-ups
Can this be faster for a fixed alphabet? Use a character-frequency tuple as the key, computing it in O(k) per string.
Does this work with uppercase letters or Unicode? Yes; sorting characters works for any Python strings.
Can groups be returned in a deterministic order? Sort the groups, or their keys, before returning them.
What if memory is limited? Consider processing input in batches or grouping externally by canonical key.
18. Given a root UIView and a target UIView, find all UIViews at the same depth as the target.
Model answer
function viewsAtTargetDepth(root, target) {
if (!root || !target) return [];
// Find the target's depth using breadth-first traversal.
const queue = [[root, 0]];
let targetDepth = null;
for (let head = 0; head < queue.length; head++) {
const [view, depth] = queue[head];
if (view === target) {
targetDepth = depth;
break;
}
for (const subview of view.subviews ?? []) {
queue.push([subview, depth + 1]);
}
}
// A target outside the root's view hierarchy has no matching depth.
if (targetDepth === null) return [];
// Collect every view at that depth.
const result = [];
for (let head = 0; head < queue.length; head++) {
const [view, depth] = queue[head];
if (depth === targetDepth) result.push(view);
}
return result;
}
This models UIView nodes with a subviews array; in Swift, the same traversal uses view.subviews and object identity (===).
The root is at depth 0. If the target is not a descendant of the root, the function returns an empty array.
Complexity: Time O(n), space O(n), where n is the number of views visited.
System designHardGrabMobile EngineerTechnical Interview 2
19. Design an iOS app for booking a cab, including the booking, payment, and feedback screens.
Model answer
1. Requirements & scale
Functional requirements
Let a rider set pickup and destination, choose a ride type, see an estimate, and book.
Show driver assignment and trip progress; support cancellation and payment.
Collect a rating and optional feedback after the trip.
Handle retries, app suspension, flaky networks, and payment-provider callbacks safely.
Non-functional requirements
Keep booking actions responsive and prevent duplicate bookings or charges.
Protect location and payment data; meet local privacy and payment requirements.
Recover the correct trip state when the app restarts or returns from the background.
Estimate: Assume 1 million daily active riders and 2 bookings per rider per month: about 2 million trips/month, or 0.8 trips/second on average. At a 50x peak, booking traffic is about 40 requests/second; quote and location-update traffic may be 10–20x higher. At roughly 5 KB of durable trip metadata per trip, trip records add about 10 GB/month before indexes and replication. Live locations are transient and should not be stored as trip history.
2. High-level architecture
The iOS app owns fast, resilient presentation and local state; backend services remain authoritative for quotes, assignment, trip status, payments, and feedback.
flowchart TD
subgraph Client
App[iOS app]
UI[Booking payment feedback screens]
Local[Local trip state]
App --> UI
UI --> Local
end
subgraph Edge
CDN[CDN assets]
Gateway[API gateway]
end
subgraph LoadBalancer
LB[Regional load balancer]
end
subgraph Services
BFF[Mobile BFF]
Trip[Trip service]
Dispatch[Dispatch service]
Pay[Payment service]
Feedback[Feedback service]
Notify[Realtime notification service]
end
subgraph Cache
Redis[Redis quotes and trip state]
end
subgraph Datastores
SQL[Trip and payment SQL]
Events[Trip event store]
Blob[Feedback media object store]
end
subgraph MessageQueue
Queue[Trip and payment events]
end
subgraph Workers
Worker[Notification and reconciliation workers]
Provider[Payment provider]
end
App -->|assets| CDN
App -->|HTTPS API| Gateway
App -->|trip updates| Notify
Gateway --> LB
LB --> BFF
BFF -->|quote and booking| Trip
Trip -->|driver match| Dispatch
BFF -->|payment methods| Pay
BFF -->|rating| Feedback
Trip --> Redis
Trip --> SQL
Pay --> SQL
Feedback --> SQL
Feedback --> Blob
Trip -->|trip events| Queue
Pay -->|payment events| Queue
Queue --> Worker
Worker -->|push and reconcile| Notify
Pay -->|authorize or capture| Provider
Notify -->|status updates| App
Diagram
3. API design
GET /v1/quotes?pickup=...&dropoff=... — return fare range, ETA, and available ride types.
POST /v1/trips — create a booking with ride type, locations, quote ID, payment method, and an Idempotency-Key.
GET /v1/trips/{tripId} — restore authoritative trip and payment state after reconnect or app relaunch.
POST /v1/trips/{tripId}/cancel — request cancellation; return any applicable fee.
POST /v1/trips/{tripId}/payment-method — select or update the method before the allowed payment state.
POST /v1/trips/{tripId}/feedback — submit rating, tags, and optional comment; accept an idempotency key.
Use authenticated HTTPS. Stream trip status over a WebSocket when available, with push notifications and polling as fallbacks.
4. Data model & storage
SQL:Trip(trip_id, rider_id, status, pickup, dropoff, quote_id, fare, version, created_at), Payment(trip_id, provider_ref, status, amount, idempotency_key), and Feedback(trip_id, rating, tags, comment_ref). Partition large trip tables by region and time; index rider ID plus creation time. Enforce one feedback record per trip.
Redis: short-lived quotes and hot trip snapshots, with TTLs. Treat it as a cache, not the source of truth.
Event log and queue: append trip/payment status changes for downstream notifications, analytics, and reconciliation. Store optional feedback media in object storage behind a short-lived upload URL.
Keep card details with a tokenized payment provider; the app and trip database store only a provider token/reference.
5. Deep dive
The key design point is making booking and payment safe across retries and asynchronous driver matching. The app shows explicit states: quote, booking pending, driver assigned, in trip, payment pending/complete, and feedback submitted. A versioned trip snapshot plus server events prevents stale updates from moving the UI backward.
sequenceDiagram
participant App as iOS app
participant API as Mobile BFF
participant Trip as Trip service
participant Pay as Payment service
participant Queue as Event queue
participant Driver as Dispatch service
App->>API: Create trip with idempotency key
API->>Trip: Validate quote and create pending trip
Trip->>Pay: Authorize payment if required
Pay-->>Trip: Authorization result
Trip->>Queue: Publish trip requested
Trip->>Driver: Request matching
Driver-->>Trip: Driver assigned
Trip-->>App: Trip snapshot and version
App->>API: Submit feedback after completion
API->>Trip: Verify completed trip
Trip-->>App: Feedback accepted
Diagram
Persist the idempotency key and its result so a timeout followed by a retry returns the original trip. Use a transactional outbox when writing a trip and publishing its event, avoiding a committed booking with a lost dispatch message. Payment webhooks are also idempotent; reconciliation workers resolve delayed or contradictory provider results. If payment authorization fails, do not dispatch; show a recoverable payment error. If matching times out, expose cancellation or retry without creating another trip.
For iOS, build the screens from a shared trip state model, with separate booking, payment, and feedback view models. Keep navigation state-restorable, validate inputs locally, and make loading, empty, error, and accessibility states first-class. Never optimistically claim a booking or payment succeeded before the server confirms it.
6. Scale, bottlenecks & trade-offs
Run stateless API services across availability zones; replicate SQL and fail over by region. Route a trip to a home region to preserve ordered writes, while allowing cached reads elsewhere.
Dispatch and location updates are likely hotter than booking writes. Partition their streams by geographic cell and trip ID; apply backpressure and coalesce frequent location updates.
Prefer strong consistency for trip creation, payment state, and feedback uniqueness. Use eventual consistency for analytics and notifications. During a regional outage, fail safely rather than confirm an unpersisted booking.
WebSockets provide timely updates but consume connections; push and polling are fallbacks. Cache quotes only briefly and revalidate price at booking, trading some speed for fare correctness.
A provider outage can delay payment confirmation. Show a pending state, reconcile asynchronously, and prevent a second charge rather than guessing success.
Yes. Test-driven development (TDD) is a short feedback loop in which I write a test before implementing the behavior, then use that test to guide the smallest useful change.
Red — write a failing test. Start with a specific expected behavior, including an edge case. For example, for a decoder, test that "226" returns 3 and "06" returns 0. Confirm the test fails for the intended reason, rather than because the test setup is broken.
Green — implement the minimum. Add only enough production code to make the new test pass. Run the focused test, then the relevant broader suite.
Refactor — improve safely. Simplify or restructure the code while keeping tests green. Add tests for newly discovered boundary cases and regressions.
Repeat at the right level. I use unit tests for isolated logic, integration tests for component boundaries, and a smaller set of UI or end-to-end tests for important user journeys.
flowchart LR
A[Write a failing test] --> B[Run test and confirm failure]
B --> C[Implement the smallest change]
C --> D[Run tests and confirm success]
D --> E[Refactor with tests passing]
E --> A
Diagram
In mobile development, I’d keep business logic testable outside UIKit where practical, inject dependencies such as network clients, and avoid making tests depend on timing or live services. TDD is a tool, not a rule: it works especially well for logic with clear expected outcomes, while exploratory UI work may need prototypes first. The important discipline is a fast, reliable feedback loop and tests that protect behavior rather than merely mirror implementation.
Practice these out loud, don't memorise them
Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.