Skip to content

Commit

Permalink
Refactor solutions for Valid Parentheses and Insert Interval
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Feb 9, 2024
1 parent 26c5865 commit 54513f6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 29 deletions.
42 changes: 22 additions & 20 deletions Sort/InsertInterval.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,29 @@

class InsertInterval {
func insert(_ intervals: [Interval], _ newInterval: Interval) -> [Interval] {
var index = 0
var result: [Interval] = []
var tempInterval = Interval(newInterval.start, newInterval.end)

while index < intervals.count && newInterval.start > intervals[index].end {
result.append(intervals[index])
index += 1
}

while index < intervals.count && newInterval.end >= intervals[index].start {
let minStart = min(tempInterval.start, intervals[index].start)
let maxEnd = max(tempInterval.end, intervals[index].end)
tempInterval = Interval(minStart, maxEnd)
index += 1
var res = [Interval](), insertIdx = 0

for (i, interval) in intervals.enumerated() {
if interval.isOverlap(with: newInterval) {
newInterval.start = min(newInterval.start, interval.start)
newInterval.end = max(newInterval.end, interval.end)
} else {
if interval.end < newInterval.start {
insertIdx += 1
}

res.append(interval)
}
}
result.append(tempInterval)

for i in index ..< intervals.count {
result.append(intervals[i])

res.insert(newInterval, at: insertIdx)

return res
}

extension Interval {
func isOverlap(with interval: Interval) -> Bool {
return start <= interval.end && end >= interval.start
}

return result
}
}
21 changes: 12 additions & 9 deletions Stack/ValidParentheses.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,28 @@
class ValidParentheses {
func isValid(_ s: String) -> Bool {
var stack = [Character]()

for char in s {
if char == "(" || char == "[" || char == "{" {
switch char {
case "(", "[", "{":
stack.append(char)
} else if char == ")" {
guard stack.count != 0 && stack.removeLast() == "(" else {
case ")":
if stack.popLast() != "(" {
return false
}
} else if char == "]" {
guard stack.count != 0 && stack.removeLast() == "[" else {
case "]":
if stack.popLast() != "[" {
return false
}
} else if char == "}" {
guard stack.count != 0 && stack.removeLast() == "{" else {
case "}":
if stack.popLast() != "{" {
return false
}
default:
continue
}
}

return stack.isEmpty
}
}

0 comments on commit 54513f6

Please sign in to comment.