diff --git a/src/my_project/interviews/amazon_high_frequency_23/round_7/jump_game_ii.py b/src/my_project/interviews/amazon_high_frequency_23/round_7/jump_game_ii.py new file mode 100644 index 00000000..1ef43897 --- /dev/null +++ b/src/my_project/interviews/amazon_high_frequency_23/round_7/jump_game_ii.py @@ -0,0 +1,33 @@ +from typing import List + +class Solution: + def jump(self, nums: List[int]) -> int: + """ + Greedy approach: At each position, jump to the farthest reachable index + + Example: [2,3,1,1,4] + - From index 0 (value=2): can reach indices 1,2 + - Greedy choice: Jump to index 1 (value=3) because it reaches farthest + - From index 1: can reach indices 2,3,4 (end) + - Answer: 2 jumps + """ + + if len(nums) <= 1: + return 0 + + jumps = 0 + current_end = 0 # End of current jump range + farthest = 0 # The farthest position we can reach + + for i in range(len(nums) - 1): + # Update farthest position reachable + farthest = max(farthest, i + nums[i]) + + # If we've reached the end of current jump range + if i == current_end: + jumps += 1 + current_end = farthest # Make the greedy choice + + if current_end > len(nums) - 1: + break + return jumps \ No newline at end of file diff --git a/src/my_project/interviews/google_top_exercises/round_1/26_rotting_oranges.py b/src/my_project/interviews/google_top_exercises/round_1/26_rotting_oranges.py new file mode 100644 index 00000000..f5213e85 --- /dev/null +++ b/src/my_project/interviews/google_top_exercises/round_1/26_rotting_oranges.py @@ -0,0 +1,38 @@ +from typing import List +from collections import deque + +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + freshy = 0 + time = 0 + m = len(grid) + n = len(grid[0]) + + q = deque() + + # Queue all rotten oranges and count fresh ones + for r in range(m): + for c in range(n): + if grid[r][c] == 1: + freshy += 1 + if grid[r][c] == 2: + q.append((r, c)) + + # Run multi-source BFS + while q: + rotten_oranges = 0 + for _ in range(len(q)): + r, c = q.popleft() + for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]: + new_r, new_c = r + dr, c + dc + if 0 <= new_r < m and 0 <= new_c < n and grid[new_r][new_c] == 1: + + q.append((new_r, new_c)) + grid[new_r][new_c] = 2 + freshy -= 1 + rotten_oranges += 1 + + if rotten_oranges > 0: + time += 1 + + return time if freshy == 0 else -1 \ No newline at end of file