Leetcode 1389: Create Target Array in the Given Order

grid47
grid47
Exploring patterns and algorithms
Jun 21, 2024 5 min read

Given two arrays of integers nums and index, the task is to create a target array by inserting elements of nums at the positions specified by index. After processing all elements, return the target array.
Problem
Approach
Steps
Complexity
Input: You are given two arrays: nums and index. The length of both arrays is the same, and nums[i] represents the element to be inserted at index[i] position in the target array.
Example: For nums = [5, 10, 20, 30, 40], index = [0, 1, 2, 2, 1], the target array will be [5, 40, 10, 30, 20].
Constraints:
• 1 <= nums.length, index.length <= 100
• nums.length == index.length
• 0 <= nums[i] <= 100
• 0 <= index[i] <= i
Output: Return the target array after inserting all elements from nums at the corresponding indices from index.
Example: For nums = [5, 10, 20, 30, 40] and index = [0, 1, 2, 2, 1], the output will be [5, 40, 10, 30, 20].
Constraints:
• The output will always be a valid array.
Goal: The goal is to insert elements from nums at positions specified by index, maintaining the order of elements in nums.
Steps:
• 1. Initialize an empty target array.
• 2. Iterate over the nums and index arrays.
• 3. Insert nums[i] at the position index[i] in the target array.
• 4. Return the target array after all insertions.
Goal: The function must handle arrays of length up to 100 efficiently.
Steps:
• nums and index arrays will have equal lengths.
• The value of index[i] will always be a valid position for insertion.
Assumptions:
• The insertion operations will always be valid.
Input: For nums = [5, 10, 20, 30, 40] and index = [0, 1, 2, 2, 1], the target array becomes [5, 40, 10, 30, 20].
Explanation: The algorithm inserts elements at positions defined by index, and we keep track of the current state of the target array.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus