TikTok OA Interview Question: People Visible to the Camera

14 Views
No Comments

There are people in a line filming a TikTok. You are given an integer array heights of size n that represents the heights of the people in the line.

The camera is to the right of the people. A person can be seen in the recording if the person can see the camera without obstructions. Formally, a person can be seen if all the people to their right have a smaller height.

Return a list of indices (0-indexed) of people that will be seen by the camera, sorted in increasing order.

Example 1:

Input: heights = [4,2,3,1]
Output: [0,2,3]
Explanation: Person 1 (0-indexed) will not be seen because person 2 is taller.

Example 2:

Input: heights = [4,3,2,1]
Output: [0,1,2,3]
Explanation: All the people will be seen by the camera!

Example 3:

Input: heights = [1,3,2,4]
Output: [3]
Explanation: Only person 3 will be seen by the camera.

The key idea is to scan from right to left while tracking the tallest person seen so far on the right. A person is visible only if their height is greater than every person to their right. This can be solved in linear time with a simple reverse traversal, and it naturally matches the examples where only the rightmost maxima remain visible.

END
 0