Practice/Google/Remove Duplicates with Order Preservation
CodingMust
You are given an array of integers and an ordering instruction. Your task is to eliminate all duplicate values from the array while controlling the final arrangement of the unique elements.
The ordering instruction can be one of two values:
"original": Keep the unique elements in the same order as their first appearance"reverse": Keep the unique elements but reverse their order after deduplicationWhen a value appears multiple times, only its first occurrence should be considered for position purposes.
Example 1:
Input: arr = [3, 1, 2, 1, 3, 4, 2], order = "original" Output: [3, 1, 2, 4] Explanation: We keep the first occurrence of each number (3, 1, 2, 4) and maintain their original sequence.
Example 2:
Input: arr = [3, 1, 2, 1, 3, 4, 2], order = "reverse" Output: [4, 2, 1, 3] Explanation: First we get unique elements [3, 1, 2, 4], then reverse to get [4, 2, 1, 3].
Example 3:
Input: arr = [5, 5, 5], order = "original" Output: [5] Explanation: All elements are duplicates, only one 5 remains.
Example 4:
Input: arr = [], order = "reverse" Output: [] Explanation: Empty array remains empty regardless of ordering.