Problem Description
Given two arrays keysArr and valuesArr of equal length, create a new object where each key-value pair is formed by keysArr[i] and valuesArr[i]. If a duplicate key (after converting to a string) appears later, it should be ignored and only the first occurrence maintained. If a key is not a string, it must be converted using String() before adding.
Key Insights
- Iterate over the arrays simultaneously.
- Convert each key to a string using String() (or equivalent in each language).
- Use a data structure (like a set) to track keys that have already been added.
- Only add a key-value pair if the key (after conversion) is not already present.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the arrays (each element is processed once).
Space Complexity: O(n), for storing the keys in an auxiliary set and the k-v pairs in the object.
Solution
The approach is to iterate index-by-index over keysArr and valuesArr. For each index, convert keysArr[i] to its string representation. Maintain a set of seen keys to check if the current key has been added before. If not, add the key and its corresponding value to the result object. This ensures that any duplicate key (after conversion to string) is ignored after its first occurrence. This method uses a hash set for fast O(1) lookups and yields an overall O(n) runtime.