TikTok OA Interview Questions: Ocean View Buildings and Minimum Operations to Make Array Palindromic

18 Views
No Comments

The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.

Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.

Example 1:

Input: heights = [4,2,3,1]
Output: [0,2,3]

Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.

Example 2:

Input: heights = [4,3,2,1]
Output: [0,1,2,3]

Explanation: All the buildings have an ocean view.

Example 3:

Input: heights = [1,3,2,4]
Output: [3]

Explanation: Only building 3 has an ocean view.

You are given an array nums consisting of positive integers.

You can perform the following operation on the array any number of times:

  • Choose any two adjacent elements and replace them with their sum.

For example, if nums = [1,2,3,1], you can apply one operation to make it [1,5,1].

Return the minimum number of operations needed to turn the array into a palindrome.

Example 1:

Input: nums = [4,3,2,1,2,3,1]
Output: 2

Explanation: We can turn the array into a palindrome in 2 operations as follows:

  • Apply the operation on the fourth and fifth element of the array, nums becomes equal to [4,3,2,3,3,1].
  • Apply the operation on the fifth and sixth element of the array, nums becomes equal to [4,3,2,3,4].

The array [4,3,2,3,4] is a palindrome. It can be shown that 2 is the minimum number of operations needed.

Example 2:

Input: nums = [1,2,3,4]
Output: 3

Explanation: We do the operation 3 times in any position; at the end, we obtain the array [10], which is a palindrome.

These TikTok interview questions focus on two common array techniques. The first problem, Ocean View Buildings, is solved by scanning from right to left while tracking the tallest building seen so far; a building has an ocean view only if it is taller than every building to its right, so the answer is collected in linear time. The second problem, Minimum Operations to Make Array Palindromic, uses a two-pointer greedy approach: compare the sums from both ends, move inward when they match, and merge the smaller side when they do not. Because all numbers are positive, this greedy strategy gives the minimum number of merges in O(n) time.

END
 0