-
Notifications
You must be signed in to change notification settings - Fork 0
/
CheckArrayFormationThroughConcatenation.java
58 lines (47 loc) · 1.41 KB
/
CheckArrayFormationThroughConcatenation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package arrays;
import utils.LeetCode;
import utils.Level;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@LeetCode(
no=1640,
title = " Check Array Formation Through Concatenation",
url = "https://leetcode.com/problems/check-array-formation-through-concatenation/",
level = Level.EASY
)
public class CheckArrayFormationThroughConcatenation {
public boolean canFormArray(int[] arr, int[][] pieces) {
boolean truth[]= new boolean[arr.length];
Arrays.fill(truth,false);
Map<Integer,Integer>pos= new HashMap<>();
for(int i=0;i<arr.length;i++){
pos.put(arr[i],i);
}
for(int i=0; i<pieces.length;i++){
int piece[]=pieces[i];
boolean valid= validate(piece, pos,truth );
if(!valid)
return valid;
}
for(boolean x:truth){
if(!x){
return x;
}
}
return true;
}
boolean validate(int []piece, Map<Integer, Integer> pos, boolean truth[]){
if(pos.get(piece[0])==null)
return false;
int firstPos=pos.get(piece[0]);
for(int i=0;i<piece.length;i++){
int x=piece[i];
if(pos.get(x)==null || pos.get(x)!=firstPos)
return false;
firstPos++;
truth[pos.get(x)]=true;
}
return true;
}
}