TIP102 Unit 3 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
ratings
of non-negative integers where each element represents a show's rating.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Apply the specified operation on each element, and then use a two-pointer technique to shift all zeros to the end of the array.
1. Iterate through the `ratings` array:
1. If `ratings[i]` is equal to `ratings[i + 1]`, multiply `ratings[i]` by 2 and set `ratings[i + 1]` to 0.
2. After processing the array, use two pointers to move all non-zero elements to the beginning and shift zeros to the end:
1. Initialize `left` pointer to track the position to place the non-zero element.
2. Traverse the array with the `right` pointer:
1. If the element at `right` is non-zero, swap it with the element at `left` and increment `left`.
2. Continue moving `right` through the array.
3. Return the modified `ratings` array.
⚠️ Common Mistakes
def apply_rating_operations(ratings):
n = len(ratings)
# Step 1: Apply the operations on the ratings array
for i in range(n - 1):
if ratings[i] == ratings[i + 1]:
ratings[i] *= 2
ratings[i + 1] = 0
# Step 2: Use two pointers to shift all zeros to the end
left = 0 # Pointer to track the position to place the non-zero element
right = 0 # Pointer to traverse the array
# Traverse the array with the right pointer
while right < n:
if ratings[right] != 0:
# Swap non-zero element with the element at the left pointer
ratings[left], ratings[right] = ratings[right], ratings[left]
left += 1
right += 1
return ratings