File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/verifying-an-alien-dictionary/
3
+ * Primary idea: Compare words one by one and make sure they are following the order
4
+ *
5
+ * Time Complexity: O(n), Space Complexity: O(n)
6
+ *
7
+ */
8
+
9
+ class VerifyingAlienDictionary {
10
+ func isAlienSorted( _ words: [ String ] , _ order: String ) -> Bool {
11
+ let charToOrder = Dictionary ( uniqueKeysWithValues: order. enumerated ( ) . map { ( $0. 1 , $0. 0 ) } )
12
+
13
+ for i in 0 ..< words. count - 1 {
14
+ let currentWord = Array ( words [ i] ) , nextWord = Array ( words [ i + 1 ] )
15
+ var j = 0
16
+
17
+ while j < min ( currentWord. count, nextWord. count) {
18
+ let currentChar = currentWord [ j] , nextChar = nextWord [ j]
19
+
20
+ guard currentChar != nextChar else {
21
+ j += 1
22
+ continue
23
+ }
24
+
25
+ if charToOrder [ currentChar] ! > charToOrder [ nextChar] ! {
26
+ return false
27
+ } else {
28
+ break
29
+ }
30
+ }
31
+
32
+ // edge case: "apple" vs. "app"; "kuvp" vs. "q"
33
+ if j == nextWord. count && currentWord. count > nextWord. count {
34
+ return false
35
+ }
36
+ }
37
+
38
+ return true
39
+ }
40
+ }
Original file line number Diff line number Diff line change 42
42
## Array
43
43
| Title | Solution | Difficulty | Time | Space |
44
44
| ----- | -------- | ---------- | ---- | ----- |
45
+ [ Verify an Alien Dictionary] ( https://leetcode.com/problems/verifying-an-alien-dictionary/ ) |[ Swift] ( Array/VerifyingAlienDictionary.swift ) | Easy| O(n)| O(n)|
45
46
[ Sort Array By Parity] ( https://leetcode.com/problems/sort-array-by-parity/ ) |[ Swift] ( Array/SortArrayByParity.swift ) | Easy| O(n)| O(n)|
46
47
[ Max Consecutive Ones] ( https://leetcode.com/problems/max-consecutive-ones/ ) | [ Swift] ( ./Array/MaxConsecutiveOnes.swift ) | Easy| O(n)| O(1)|
47
48
[ Heaters] ( https://leetcode.com/problems/heaters/ ) | [ Swift] ( ./Array/Heaters.swift ) | Easy| O(nlogn)| O(1)|
You can’t perform that action at this time.
0 commit comments