File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change @@ -134,4 +134,30 @@ String intToRoman(int num) {
134134
135135 return result.join();
136136}
137+ ```
138+
139+ ### Validate Stack Sequences
140+
141+ ``` dart
142+ bool validateStackSequences(List<int> pushed, List<int> popped) {
143+ List<int> current = [];
144+ int indexPush = 0;
145+ int indexPop = 0;
146+
147+ while (indexPush < pushed.length - 1 || indexPop < popped.length - 1) {
148+ if (current.contains(popped[indexPop])) {
149+ if (current.last == popped[indexPop]) {
150+ current.removeLast();
151+ indexPop++;
152+ } else {
153+ return false;
154+ }
155+ } else {
156+ current.add(pushed[indexPush]);
157+ indexPush++;
158+ }
159+ }
160+
161+ return true;
162+ }
137163```
Original file line number Diff line number Diff line change 1+ void main (List <String > args) {
2+ List <List <List <int >>> cases = [
3+ [
4+ [1 , 2 , 3 , 4 , 5 ],
5+ [4 , 5 , 3 , 2 , 1 ]
6+ ],
7+ [
8+ [1 , 2 , 3 , 4 , 5 ],
9+ [4 , 3 , 5 , 1 , 2 ]
10+ ]
11+ ];
12+
13+ for (final testcase in cases) {
14+ print (validateStackSequences (testcase.first, testcase.last));
15+ }
16+ }
17+
18+ bool validateStackSequences (List <int > pushed, List <int > popped) {
19+ List <int > current = [];
20+ int indexPush = 0 ;
21+ int indexPop = 0 ;
22+
23+ while (indexPush < pushed.length - 1 || indexPop < popped.length - 1 ) {
24+ if (current.contains (popped[indexPop])) {
25+ if (current.last == popped[indexPop]) {
26+ current.removeLast ();
27+ indexPop++ ;
28+ } else {
29+ return false ;
30+ }
31+ } else {
32+ current.add (pushed[indexPush]);
33+ indexPush++ ;
34+ }
35+ }
36+
37+ return true ;
38+ }
You can’t perform that action at this time.
0 commit comments