Skip to content

Commit 7f18229

Browse files
solves check array formation through concatenation
1 parent d8db1eb commit 7f18229

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@
406406
| 1624 | [Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters) | [![Java](assets/java.png)](src/LargestSubStringBetweenTwoEqualCharacters.java) | |
407407
| 1629 | [Slowest Key](https://leetcode.com/problems/slowest-key) | [![Java](assets/java.png)](src/SlowestKey.java) | |
408408
| 1636 | [Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency) | [![Java](assets/java.png)](src/SortArrayByIncreasingFrequency.java) | |
409-
| 1640 | [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation) | | |
409+
| 1640 | [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation) | [![Java](assets/java.png)](src/CheckArrayFormationThroughConcatenation.java) | |
410410
| 1646 | [Get Maximum in Generated Array](https://leetcode.com/problems/get-maximum-in-generated-array) | | |
411411
| 1652 | [Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb) | | |
412412
| 1656 | [Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream) | | |

Diff for: src/CheckArrayFormationThroughConcatenation.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class CheckArrayFormationThroughConcatenation {
5+
public boolean canFormArray(int[] arr, int[][] pieces) {
6+
final Map<Integer, Integer> positions = getPositions(arr);
7+
for (int[] piece : pieces) {
8+
if (!positions.containsKey(piece[0])) return false;
9+
if (positions.get(piece[0]) + piece.length > arr.length) return false;
10+
for (int i = 0, j = positions.get(piece[0]); i < piece.length ; i++, j++) {
11+
if (piece[i] != arr[j]) return false;
12+
}
13+
}
14+
return true;
15+
}
16+
17+
private Map<Integer, Integer> getPositions(int[] array) {
18+
final Map<Integer, Integer> positions = new HashMap<>();
19+
for (int index = 0 ; index < array.length ; index++) {
20+
positions.put(array[index], index);
21+
}
22+
return positions;
23+
}
24+
}

0 commit comments

Comments
 (0)