Skip to content

[doitduri] WEEK 06 solutions #1432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions container-with-most-water/doitduri.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution {
func maxArea(_ height: [Int]) -> Int {
var start = 0
var end = height.count - 1
var result = 0

while start < end {
let width = end - start
let waters = width * (min(height[start], height[end]))

result = max(result, waters)

if height[start] > height[end] {
end = end - 1
} else {
start = start + 1
}
}

return result
}
}
57 changes: 57 additions & 0 deletions design-add-and-search-words-data-structure/doitduri.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
class WordDictionary {
class TrieNode {
var children: [Character: TrieNode] = [:]
var isEndOfWord: Bool = false
}

private let root: TrieNode

init() {
root = TrieNode()
}

func addWord(_ word: String) {
let key = word.lowercased()
var current = root

for char in key {
if current.children[char] == nil {
current.children[char] = TrieNode()
}

if let node = current.children[char] {
current = node
}
}

current.isEndOfWord = true
}

func search(_ word: String) -> Bool {
let key = word.lowercased()
return searchInNode(Array(key), 0, root)
}

private func searchInNode(_ word: [Character], _ index: Int, _ node: TrieNode) -> Bool {
if index == word.count {
return node.isEndOfWord
}

let currentChar = word[index]

if currentChar == "." {
for (_, childNode) in node.children {
if searchInNode(word, index + 1, childNode) {
return true
}
}
return false
} else {
guard let nextNode = node.children[currentChar] else {
return false
}

return searchInNode(word, index + 1, nextNode)
}
}
}
23 changes: 23 additions & 0 deletions valid-parentheses/doitduri.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
func isValid(_ s: String) -> Bool {
let pair: [Character: Character] = [
"(": ")",
"[": "]",
"{": "}"
]

var stack: [Character] = []

for char in s {
if pair.keys.contains(char) {
stack.append(char)
} else {
if stack.isEmpty || pair[stack.removeLast()] != char {
return false
}
}
}

return stack.isEmpty
}
}