#1929

Concatenation of Array

Easy
ArraySimulationArraySimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach involves directly filling the new array in a single pass. This is efficient and leverages the structure of the problem, reducing the need for multiple loops.

⚙️

Algorithm

2 steps
  1. 1Step 1: Create an empty array 'ans' of size 2 * n.
  2. 2Step 2: Loop through the original array 'nums' once, and for each index i, set ans[i] = nums[i] and ans[i + n] = nums[i].
solution.py6 lines
1nums = [1, 2, 1]
2ans = [0] * (2 * len(nums))
3for i in range(len(nums)):
4    ans[i] = nums[i]
5    ans[i + len(nums)] = nums[i]
6print(ans)

Complexity note: This complexity is linear because we only loop through the input array once. The space complexity is O(n) due to the creation of the new array of size 2n.

  • 1The problem requires understanding how to manipulate array indices effectively.
  • 2Recognizing patterns in array manipulation can lead to more efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.