Skip to content

Commit 358edba

Browse files
authored
Create 3069-distribute-elements-into-two-arrays-i.java
1 parent 1aa26a8 commit 358edba

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Title: 3002. Result Array After Splitting
3+
* Link: https://leetcode.com/problems/result-array-after-splitting/
4+
*
5+
* Problem:
6+
* You are given an integer array nums.
7+
* You must split it into two arrays list1 and list2 such that:
8+
* - list1 starts with nums[0]
9+
* - list2 starts with nums[1]
10+
* - For every i from 2 to n-1, compare the last elements of list1 and list2:
11+
* -> If last element of list1 > last element of list2, put nums[i] in list1
12+
* -> Otherwise, put nums[i] in list2
13+
* Finally, return the concatenation of list1 followed by list2.
14+
*
15+
* Approach:
16+
* - Initialize list1 with nums[0] and list2 with nums[1].
17+
* - Traverse nums from index 2.
18+
* - At each step, compare the last element of list1 and list2.
19+
* - Place nums[i] into the list whose last element is greater (list1) or smaller (list2).
20+
* - After traversal, build the final result array by appending list1 followed by list2.
21+
*
22+
* Dry Run:
23+
* Example: nums = [2, 1, 3, 3]
24+
* list1 = [2], list2 = [1]
25+
* i=2 → compare lastList1=2, lastList2=1 → list1 wins → list1=[2,3]
26+
* i=3 → compare lastList1=3, lastList2=1 → list1 wins → list1=[2,3,3]
27+
* Final result = [2,3,3,1]
28+
*
29+
* Time Complexity: O(n) → single pass over nums, building result in linear time
30+
* Space Complexity: O(n) → extra space used for list1 and list2
31+
*/
32+
33+
class Solution {
34+
public int[] resultArray(int[] nums) {
35+
int length = nums.length;
36+
37+
List<Integer> list1 = new ArrayList<>();
38+
List<Integer> list2 = new ArrayList<>();
39+
40+
list1.add(nums[0]);
41+
list2.add(nums[1]);
42+
43+
for (int i = 2; i < length; i++) {
44+
int lastList1 = list1.get(list1.size() - 1);
45+
int lastList2 = list2.get(list2.size() - 1);
46+
47+
if (lastList1 > lastList2) {
48+
list1.add(nums[i]);
49+
} else {
50+
list2.add(nums[i]);
51+
}
52+
}
53+
54+
int[] ans = new int[length];
55+
int index = 0;
56+
for (int ele : list1) {
57+
ans[index++] = ele;
58+
}
59+
for (int ele : list2) {
60+
ans[index++] = ele;
61+
}
62+
return ans;
63+
}
64+
}

0 commit comments

Comments
 (0)