Skip to content

Commit a537cbc

Browse files
committed
10 problems
1 parent 77fe36e commit a537cbc

10 files changed

+322
-11
lines changed

leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1249_Minimum_Remove_to_Make_Valid_Parentheses.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,43 @@ class Solution {
2828
return resultString
2929
}
3030
}
31+
32+
33+
34+
class Solution {
35+
func minRemoveToMakeValid(_ s: String) -> String {
36+
var sArray = Array(s), stack = [Character](), leftCount = 0, rightCount = 0
37+
38+
for item in sArray {
39+
if item == "(" {
40+
stack.append(item)
41+
leftCount += 1
42+
} else if item == ")" {
43+
if leftCount > 0 {
44+
stack.append(item)
45+
leftCount -= 1
46+
}
47+
} else {
48+
stack.append(item)
49+
}
50+
}
51+
52+
sArray = stack
53+
stack.removeAll()
54+
55+
for item in sArray.reversed() {
56+
if item == "(" {
57+
if rightCount > 0 {
58+
stack.append(item)
59+
rightCount -= 1
60+
}
61+
} else if item == ")" {
62+
stack.append(item)
63+
rightCount += 1
64+
} else {
65+
stack.append(item)
66+
}
67+
}
68+
return stack.reversed().reduce("") { $0 + String($1) }
69+
}
70+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
func minInsertions(_ s: String) -> Int {
3+
let sArray = Array(s)
4+
var stack = [Int](), result = 0
5+
for item in sArray {
6+
if item == "(" {
7+
if let last = stack.last {
8+
if last == 2 {
9+
stack.append(2)
10+
} else {
11+
result += 1
12+
stack.removeLast()
13+
stack.append(2)
14+
}
15+
} else {
16+
stack.append(2)
17+
}
18+
} else {
19+
if let last = stack.last {
20+
if last == 2 {
21+
stack.removeLast()
22+
stack.append(1)
23+
} else {
24+
stack.removeLast()
25+
}
26+
} else {
27+
result += 1
28+
stack.append(1)
29+
}
30+
}
31+
}
32+
result += stack.reduce(0) { $0 + $1 }
33+
return result
34+
}
35+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Main Idea: https://tinyurl.com/y4dtahmr
2+
class Solution {
3+
func containsCycle(_ grid: [[Character]]) -> Bool {
4+
var visited = Array(repeating: Array(repeating: false, count: grid[0].count), count: grid.count)
5+
for i in 0..<grid.count {
6+
for j in 0..<grid[0].count {
7+
if !visited[i][j] {
8+
if containsCycleHelperDFS(grid, i, j, &visited, -1, -1) {
9+
return true
10+
}
11+
}
12+
}
13+
}
14+
return false
15+
}
16+
17+
func containsCycleHelperDFS(_ grid: [[Character]], _ row: Int, _ col: Int, _ visited: inout [[Bool]], _ prevRow: Int, _ prevCol: Int) -> Bool {
18+
for (r, c) in [(0, -1), (-1, 0), (0, 1), (1, 0)] {
19+
let (newR, newC) = (row + r, col + c)
20+
if newR < 0 || newR >= grid.count || newC < 0 || newC >= grid[0].count {
21+
continue
22+
}
23+
if newR == prevRow && newC == prevCol {
24+
continue
25+
}
26+
if grid[newR][newC] == grid[row][col] {
27+
if visited[newR][newC] {
28+
return true
29+
} else {
30+
visited[newR][newC] = true
31+
if containsCycleHelperDFS(grid, newR, newC, &visited, row, col) {
32+
return true
33+
}
34+
}
35+
}
36+
}
37+
return false
38+
}
39+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
func findBuildings(_ heights: [Int]) -> [Int] {
3+
var result = [Int](), currentMaxHeight = Int.min
4+
for i in stride(from: heights.count - 1, through: 0, by: -1) {
5+
let currentHeight = heights[i]
6+
if currentHeight > currentMaxHeight {
7+
result.append(i)
8+
currentMaxHeight = currentHeight
9+
}
10+
}
11+
return result.reversed()
12+
}
13+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import Foundation
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* public class TreeNode {
6+
* public var val: Int
7+
* public var left: TreeNode?
8+
* public var right: TreeNode?
9+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
10+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
11+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
12+
* self.val = val
13+
* self.left = left
14+
* self.right = right
15+
* }
16+
* }
17+
*/
18+
19+
// DFS. Wrong answer
20+
class Solution {
21+
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
22+
var heightNodeMap = [Int:[Int]]()
23+
verticalOrderDFSHelper(root, 0, &heightNodeMap)
24+
25+
var result = [[Int]]()
26+
for key in heightNodeMap.keys.sorted() {
27+
result.append(heightNodeMap[key]!.sorted())
28+
}
29+
return result
30+
}
31+
32+
func verticalOrderDFSHelper(_ root: TreeNode?, _ horrizotalDistace: Int, _ heightNodeMap: inout [Int:[Int]]) {
33+
guard let root = root else {
34+
return
35+
}
36+
37+
heightNodeMap[horrizotalDistace, default: [Int]()].append(root.val)
38+
verticalOrderDFSHelper(root.left, horrizotalDistace - 1, &heightNodeMap)
39+
verticalOrderDFSHelper(root.right, horrizotalDistace + 1, &heightNodeMap)
40+
}
41+
}
42+
43+
// BFS. Accepted
44+
class Solution {
45+
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
46+
guard let root = root else {
47+
return []
48+
}
49+
var heightNodeMap = [Int:[Int]]()
50+
var queue = [(TreeNode, Int)]() // (TreeNode, horrizotalDistace)
51+
queue.append((root, 0))
52+
53+
while !queue.isEmpty {
54+
let (node, horrizotalDistace) = queue.removeFirst()
55+
heightNodeMap[horrizotalDistace, default: [Int]()].append(node.val)
56+
if let left = node.left {
57+
queue.append((left, horrizotalDistace - 1))
58+
}
59+
60+
if let right = node.right {
61+
queue.append((right, horrizotalDistace + 1))
62+
}
63+
}
64+
65+
var result = [[Int]](), minHorrizotalDistace = heightNodeMap.keys.min()!, maxHorrizotalDistace = heightNodeMap.keys.max()!
66+
for key in minHorrizotalDistace...maxHorrizotalDistace {
67+
result.append(heightNodeMap[key]!)
68+
}
69+
return result
70+
}
71+
}

leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.swift

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ public class Node {
1212
}
1313
}
1414

15-
import Foundation
1615
class Solution {
1716
func treeToDoublyList(_ root: Node?) -> Node? {
1817
guard let rootNode = root else {
@@ -41,3 +40,32 @@ class Solution {
4140
treeToDoublyListInorderDFSHelper(rootNode.right, &listHead, &listTail)
4241
}
4342
}
43+
44+
// More cleaner version than the above
45+
class Solution {
46+
func treeToDoublyList(_ root: Node?) -> Node? {
47+
guard let root = root else {
48+
return nil
49+
}
50+
var first: Node? = nil, last: Node? = nil // first is the smallest and last is the largest
51+
treeToDoublyListInorderDFSHelper(root, &first, &last)
52+
first!.left = last
53+
last!.right = first
54+
return first
55+
}
56+
57+
func treeToDoublyListInorderDFSHelper(_ root: Node?, _ first: inout Node?, _ last: inout Node?) {
58+
guard let root = root else {
59+
return
60+
}
61+
treeToDoublyListInorderDFSHelper(root.left, &first, &last)
62+
if last != nil {
63+
root.left = last
64+
last!.right = root
65+
} else {
66+
first = root
67+
}
68+
last = root
69+
treeToDoublyListInorderDFSHelper(root.right, &first, &last)
70+
}
71+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// https://tinyurl.com/y6s5neug
2+
class Solution {
3+
func nextGreaterElements(_ nums: [Int]) -> [Int] {
4+
var nextGreater = Array(repeating: -1, count: nums.count), stack = [Int]()
5+
let len = nums.count
6+
for i in stride(from: 2 * len - 1, through: 0, by: -1) {
7+
while !stack.isEmpty && stack.last! <= nums[i % len] {
8+
stack.removeLast()
9+
}
10+
if !stack.isEmpty && i < len {
11+
nextGreater[i] = stack.last!
12+
}
13+
stack.append(nums[i % len])
14+
}
15+
return nextGreater
16+
}
17+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import Foundation
2+
3+
// Video: https://tinyurl.com/y5bhfoze
4+
class Solution {
5+
var prefixSum = [Int]()
6+
init(_ w: [Int]) {
7+
for i in 0..<w.count {
8+
if i == 0 {
9+
prefixSum.append(w[i])
10+
} else {
11+
prefixSum.append(prefixSum.last! + w[i])
12+
}
13+
}
14+
}
15+
16+
func pickIndex() -> Int {
17+
let randWeight = Int.random(in: 1...prefixSum.last!)
18+
var left = 0, right = prefixSum.count - 1
19+
while left < right {
20+
let mid = left + (right - left) / 2
21+
if prefixSum[mid] < randWeight {
22+
left = mid + 1
23+
} else {
24+
right = mid
25+
}
26+
}
27+
28+
return left
29+
}
30+
}
Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,40 @@
11
import Foundation
22

3+
// Time: O(n^2)
34
class Solution {
45
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
5-
guard nums.count > 0 else {
6-
return 0
6+
var prefixSum = [Int]()
7+
prefixSum.append(0)
8+
for num in nums {
9+
prefixSum.append(prefixSum.last! + num)
10+
}
11+
12+
var count = 0
13+
for i in 0..<nums.count {
14+
for j in i..<nums.count {
15+
if prefixSum[j + 1] - prefixSum[i] == k {
16+
count += 1
17+
}
18+
}
719
}
8-
var prefixSumCounter = [Int:Int]()
9-
prefixSumCounter[0] = 1
10-
var (subarrayCount, currentSum) = (0, 0)
20+
return count
21+
}
22+
}
23+
24+
// Time: O(n)
25+
import Foundation
26+
class Solution {
27+
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
28+
var prefixSumCounterMap = [Int:Int](), totalCount = 0, currentSum = 0
29+
prefixSumCounterMap[0] = 1
1130
for num in nums {
1231
currentSum += num
13-
var prefixSum = currentSum - k
14-
if let count = prefixSumCounter[prefixSum] {
15-
subarrayCount += count
32+
let prevPrefixSum = currentSum - k
33+
if let currentCount = prefixSumCounterMap[prevPrefixSum] {
34+
totalCount += currentCount
1635
}
17-
prefixSumCounter[currentSum, default: 0] += 1
36+
prefixSumCounterMap[currentSum, default: 0] += 1
1837
}
19-
return subarrayCount
38+
return totalCount
2039
}
2140
}

leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/921_Minimum_Add_to_Make_Parentheses_Valid.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,22 @@ class Solution {
1616
return stack.count
1717
}
1818
}
19+
20+
21+
class Solution {
22+
func minAddToMakeValid(_ s: String) -> Int {
23+
var stack = [Character](), count = 0
24+
for char in s {
25+
if char == Character("(") {
26+
stack.append(char)
27+
} else if char == Character(")") {
28+
if !stack.isEmpty && stack.last! == Character("(") {
29+
stack.removeLast()
30+
} else {
31+
count += 1
32+
}
33+
}
34+
}
35+
return count + stack.count
36+
}
37+
}

0 commit comments

Comments
 (0)