Category: Easy
Problem
Given two arrays of integers nums
and index
. Your task is to create target array under the following rules:
- Initially target array is empty.
- From left to right read nums[i] and index[i], insert at index
index[i]
the valuenums[i]
in target array. - Repeat the previous step until there are no elements to read in
nums
andindex.
Return the target array.
It is guaranteed that the insertion operations will be valid.
https://leetcode.com/problems/create-target-array-in-the-given-order/
Examples
Example 1:
1 2 3 4 5 6 7 8 9 | Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] |
Example 2:
1 2 3 4 5 6 7 8 9 | Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Explanation: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4] |
Example 3:
1 2 | Input: nums = [1], index = [0] Output: [1] |
Constraints
1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i
Solution Approach
In this problem, we have to have an array whose values are given in another array and what value goes to what index is also provided just that an index can have many values and we have to solve that.
We can use ArrayList to do just that we will populate it using the add method at the given index and value. Add method has 2 signatures we will use the one where we can input the value as well as an index in the ArrayList. In the end, we just convert that ArrayList to an integer array and send the value as the answer.
Coming to the coding part if the length of the index array is 1 then we straightaway return the same nums array. After that, we create an array which will contain the actual array which we send from the method and an Arraylist to temporarily store the index and value. Next, to the ArrayList, we add the values of the nums array at the index’s index using the add method. Then we convert the ArrayList and its elements from Object to integer in the solution array and return the same.
Solution code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution { public int[] createTargetArray(int[] nums, int[] index) { if(index.length == 1 ){ return nums; } ArrayList tempArr = new ArrayList(); int[] solutionArray = new int[nums.length]; for(int i = 0;i<nums.length;i++){ tempArr.add(index[i],nums[i]); } for(int k = 0;k<tempArr.size();k++){ retArray[k] = (Integer)tempArr.get(k); } return retArray; } } |
For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.
Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding 🙂