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.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use the two-pointer technique to efficiently compute the squares of the engagement rates and sort them in non-decreasing order.
1. Initialize two pointers, `left` at the start of the list and `right` at the end.
2. Create a result list initialized with zeros, with the same length as the input list.
3. Iterate over the list from the end towards the beginning:
1. Compare the square of the value at `left` with the square of the value at `right`.
2. Place the larger square at the current position in the result list.
3. Move the corresponding pointer inward (left or right) based on which square was larger.
4. Decrement the position in the result list.
4. Return the result list, which contains the squared engagements in sorted order.
⚠️ Common Mistakes
Revised Two-Pointer Solution:
def engagement_boost(engagements):
n = len(engagements)
result = [0] * n
left, right = 0, n - 1
position = n - 1
while left <= right:
left_square = engagements[left] * engagements[left]
right_square = engagements[right] * engagements[right]
if left_square > right_square:
result[position] = left_square
left += 1
else:
result[position] = right_square
right -= 1
position -= 1
return result