Unit 7 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
0
since there are no 1
s in the list.0
s appearing before any 1
s.0
.HAPPY CASE
Input: rooms = [0, 0, 0, 1, 1, 1, 1]
Output: 4
Explanation: The total number of checked-in passengers is 4, corresponding to the four `1`s.
Input: rooms = [0, 0, 0, 0, 0, 1]
Output: 1
Explanation: The total number of checked-in passengers is 1, corresponding to the one `1`.
EDGE CASE
Input: rooms = [0, 0, 0, 0, 0, 0]
Output: 0
Explanation: No passengers have checked in, so return 0.
Input: rooms = [1, 1, 1, 1]
Output: 4
Explanation: All passengers have checked in, so return 4.
Match what this problem looks like to known categories of problems, e.g., Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Binary Search problems, we want to consider the following approaches:
1
, and then calculate the number of 1
s based on the list's length.Plan the solution with appropriate visualizations and pseudocode.
1) Binary Search: Perform binary search to locate the first occurrence of 1
in the list.
2) Calculate Result: Once the first occurrence is found, the number of 1
s in the list is simply the total length of the list minus the index of the first 1
.
Pseudocode:
1) Initialize `left` to 0 and `right` to `len(rooms) - 1`.
2) Initialize `first_one_index` to `len(rooms)` as a default (assuming no `1`s).
3) While `left` is less than or equal to `right`:
a) Calculate the midpoint `mid`.
b) If `rooms[mid] == 1`, update `first_one_index` to `mid` and move `right` to `mid - 1` (search the left side).
c) If `rooms[mid] == 0`, move `left` to `mid + 1` (search the right side).
4) Return the total number of `1`s as `len(rooms) - first_one_index`.
Implement the code to solve the algorithm.
def count_checked_in_passengers(rooms):
n = len(rooms)
# Binary search to find the first occurrence of 1
left, right = 0, n - 1
first_one_index = n # Assume there are no 1's initially
while left <= right:
mid = left + (right - left) // 2
if rooms[mid] == 1:
first_one_index = mid
right = mid - 1 # Look on the left side for the first 1
else:
left = mid + 1 # Look on the right side
# Number of 1's is the total length minus the index of the first 1
return n - first_one_index
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
[0, 0, 0, 1, 1, 1, 1]
:
1
appears at index 3, resulting in a total of 4 checked-in passengers.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the length of the rooms
list.
O(log N)
because we are performing binary search.O(1)
because we are using a constant amount of extra space.