Katkat

Solve three coding interview problems

GoogleSoftware Engineer · Onsite

Last updated

This set tests proficiency in recursive string decoding, dynamic programming for sequential decision-making, and graph-based traversal algorithms for grid analysis.

Part 1: Nested String Decoder

Given an encoded string where patterns are formatted as k[string], where the string inside the brackets is repeated exactly k times, return the decoded string. You may assume the input is always valid.

def decode_string(s: str) -> str:

Example: Input: s = "3[a]2[bc]" Output: "aaabcbc"

Part 2: Max Profit with Cooldown

Given an array prices where prices[i] is the price of a stock on day i, find the maximum profit you can achieve. You may complete as many transactions as you like, but you must sell before you buy again, and there is a 1-day cooldown period after selling (i.e., you cannot buy on the day after you sell).

def max_profit(prices: list[int]) -> int:

Example: Input: prices = [1, 2, 3, 0, 2] Output: 3 (Buy, Sell, Cooldown, Buy, Sell)

Part 3: Number of Islands

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

def num_islands(grid: list[list[str]]) -> int:

Example: Input: grid = [["1","1","0"],["1","1","0"],["0","0","1"]] Output: 2

Hints

Hint 1

For the decoder, use a stack to keep track of previous counts and string segments when encountering nested brackets.

Hint 2

For the stock problem, define states for each day: holding a stock, sold a stock (cooldown), or ready to buy.

Hint 3

For the island count, use either Depth-First Search (DFS) or Breadth-First Search (BFS) to mark visited land cells as water.

Follow-up questions

  • How would you modify the string decoder if 'k' could be a multi-digit number or if nesting depth was arbitrary?
  • What is the space complexity of your dynamic programming solution for the stock problem, and can it be reduced?
  • How would you handle the island counting problem if the grid was too large to fit in memory and had to be processed as a stream of chunks?