Skip to content

Commit fa1c4a9

Browse files
committed
[Array] Add a solution to Verifying an Alien Dictionary
1 parent 301c6df commit fa1c4a9

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Array/VerifyingAlienDictionary.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
## Array
4343
| Title | Solution | Difficulty | Time | Space |
4444
| ----- | -------- | ---------- | ---- | ----- |
45+
[Verify an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/)|[Swift](Array/VerifyingAlienDictionary.swift)| Easy| O(n)| O(n)|
4546
[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[Swift](Array/SortArrayByParity.swift)| Easy| O(n)| O(n)|
4647
[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)| [Swift](./Array/MaxConsecutiveOnes.swift)| Easy| O(n)| O(1)|
4748
[Heaters](https://leetcode.com/problems/heaters/)| [Swift](./Array/Heaters.swift)| Easy| O(nlogn)| O(1)|

0 commit comments

Comments
 (0)