Skip to content

Commit

Permalink
[Array] Add a solution to Verifying an Alien Dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Jan 12, 2020
1 parent 301c6df commit fa1c4a9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Array/VerifyingAlienDictionary.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Question Link: https://leetcode.com/problems/verifying-an-alien-dictionary/
* Primary idea: Compare words one by one and make sure they are following the order
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/

class VerifyingAlienDictionary {
func isAlienSorted(_ words: [String], _ order: String) -> Bool {
let charToOrder = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.1, $0.0) })

for i in 0..<words.count - 1 {
let currentWord = Array(words[i]), nextWord = Array(words[i + 1])
var j = 0

while j < min(currentWord.count, nextWord.count) {
let currentChar = currentWord[j], nextChar = nextWord[j]

guard currentChar != nextChar else {
j += 1
continue
}

if charToOrder[currentChar]! > charToOrder[nextChar]! {
return false
} else {
break
}
}

// edge case: "apple" vs. "app"; "kuvp" vs. "q"
if j == nextWord.count && currentWord.count > nextWord.count {
return false
}
}

return true
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
## Array
| Title | Solution | Difficulty | Time | Space |
| ----- | -------- | ---------- | ---- | ----- |
[Verify an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/)|[Swift](Array/VerifyingAlienDictionary.swift)| Easy| O(n)| O(n)|
[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[Swift](Array/SortArrayByParity.swift)| Easy| O(n)| O(n)|
[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)| [Swift](./Array/MaxConsecutiveOnes.swift)| Easy| O(n)| O(1)|
[Heaters](https://leetcode.com/problems/heaters/)| [Swift](./Array/Heaters.swift)| Easy| O(nlogn)| O(1)|
Expand Down

0 comments on commit fa1c4a9

Please sign in to comment.