LeetCode 1920: Build Array from Permutation Solution
Master LeetCode problem 1920 (Build Array from Permutation), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1920. Build Array from Permutation
Problem Explanation
Explanation:
To solve this problem, we can iterate through the given array nums, and for each element nums[i], we set ans[i] to be equal to nums[nums[i]]. This way, we are creating the new array ans based on the given permutation nums.
Algorithm:
- Create a new array
ansof the same length asnums. - Iterate through each index
iinnums. - Set
ans[i] = nums[nums[i]]. - Return the final array
ans.
Time Complexity: O(n) where n is the length of the input array nums.
Space Complexity: O(n) where n is the length of the input array nums.
:
Solution Code
class Solution {
public int[] buildArray(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = nums[nums[i]];
}
return ans;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1920 (Build Array from Permutation)?
This page provides optimized solutions for LeetCode problem 1920 (Build Array from Permutation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1920 (Build Array from Permutation)?
The time complexity for LeetCode 1920 (Build Array from Permutation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1920 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1920 in Java, C++, or Python.