Similar Problems
Similar Problems not available
Create Components With Same Value - Leetcode Solution
Companies:
LeetCode: Create Components With Same Value Leetcode Solution
Difficulty: Hard
Topics: math tree depth-first-search array
Problem statement:
Given an array nums of n integers, return an array of all the unique values of nums, sorted in descending order. You must write an efficient algorithm for this problem.
Example 1:
Input: nums = [1,1,2,2,2,3] Output: [3,2,1]
Example 2:
Input: nums = [4,4,4,4] Output: [4]
Solution:
The problem statement asks us to find an array of all the unique values of nums, sorted in descending order. We can use a Set to store all unique values in the array.
Steps:
- We create an empty Set and traverse the given array nums.
- We add each element of nums to the Set.
- Finally, we convert the Set back to an array and sort it in descending order.
Let's write code to implement the above steps:
public int[] uniqueDescending(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int num : nums) {
set.add(num);
}
int[] result = new int[set.size()];
int i = 0;
for (int num : set) {
result[i++] = num;
}
Arrays.sort(result);
int len = result.length;
int[] finalResult = new int[len];
for (i = 0; i < len; i++) {
finalResult[i] = result[len - i - 1];
}
return finalResult;
}
Complexity Analysis:
- Time Complexity: O(nlogn) because we are sorting the array, and the worst-case time complexity of sorting is nlogn.
- Space Complexity: O(n) because we are using a Set to store unique values and an array to store the final result, both of size n.
Create Components With Same Value Solution Code
1