LeetCode 1389: Create Target Array in the Given Order Solution

Master LeetCode problem 1389 (Create Target Array in the Given Order), 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.

1389. Create Target Array in the Given Order

Problem Explanation

Explanation:

To solve this problem, we can simulate the process of inserting elements from the given nums array into the target array at specific indices as specified by the index array.

We iterate through the nums array and for each element, we insert it into the target array at the corresponding index specified in the index array. We shift the elements in the target array to the right to make space for the new element.

The time complexity of this approach is O(n^2) where n is the length of the nums array since in the worst case, we may need to shift all elements to the right for each insertion. The space complexity is O(n) where n is the length of the nums array to store the target array.

:

Solution Code

class Solution {
    public int[] createTargetArray(int[] nums, int[] index) {
        List<Integer> target = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            target.add(index[i], nums[i]);
        }
        return target.stream().mapToInt(Integer::intValue).toArray();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1389 (Create Target Array in the Given Order)?

This page provides optimized solutions for LeetCode problem 1389 (Create Target Array in the Given Order) 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 1389 (Create Target Array in the Given Order)?

The time complexity for LeetCode 1389 (Create Target Array in the Given Order) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1389 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1389 in Java, C++, or Python.

Back to LeetCode Solutions