Skip to content

Commit 0e9d2b4

Browse files
committed
Solved some of top 150 leetcode problems
1 parent a5edfc1 commit 0e9d2b4

File tree

22 files changed

+298
-35
lines changed

22 files changed

+298
-35
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/?envType=study-plan-v2&envId=top-interview-150
4+
//Time Complexity :- O(n), space complexity is O(1)
5+
public func maxProfit(_ prices: [Int]) -> Int {
6+
var minPrice = Int.max
7+
var maxProfit = 0
8+
for price in prices {
9+
minPrice = min(price, minPrice)
10+
maxProfit = max(price - minPrice, maxProfit)
11+
}
12+
return maxProfit
13+
}
14+
15+
print("Max profit of [7,1,5,3,6,4] is :- \(maxProfit([7,1,5,3,6,4]))") //Buy on second day & sell on 5th day
16+
print("Max profit of [7,6,4,3,1] is :- \(maxProfit([7,6,4,3,1]))") //in every sell it gonna be loss
17+
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/?envType=study-plan-v2&envId=top-interview-150
4+
//Time Complexity :- O(n), space complexity is O(1)
5+
6+
func maxProfit(_ prices: [Int]) -> Int {
7+
var profit = 0
8+
for i in 1..<prices.count {
9+
if prices[i] > prices[i - 1] {
10+
profit += prices[i] - prices[i - 1]
11+
}
12+
}
13+
return profit
14+
}
15+
print("Max profit of [7,1,5,3,6,4] is :- \(maxProfit([7,1,5,3,6,4]))") //Buy on second day & sell on 5th day
16+
//[1,2,3,4,5]
17+
print("Max profit of [1,2,3,4,5] is :- \(maxProfit([1,2,3,4,5]))") //Buy on second day & sell on 5th day
18+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/candy/description/?envType=study-plan-v2&envId=top-interview-150
4+
5+
func candy(_ ratings: [Int]) -> Int {
6+
var candiesArray = Array(repeating : 1, count : ratings.count)
7+
for i in 1..<ratings.count where ratings[i] > ratings[i - 1] {
8+
candiesArray[i] = candiesArray[i - 1] + 1
9+
}
10+
for i in (0..<ratings.count - 1).reversed() where ratings[i] > ratings[i + 1] {
11+
candiesArray[i] = max(candiesArray[i], candiesArray[i + 1] + 1)
12+
}
13+
return candiesArray.reduce(0, +)
14+
}
15+
16+
print("minimum candies needed for array :- [1,0,2] is \(candy([1,0,2]))")
17+
print("minimum candies needed for array :- [5,4,3,5,6,2] is \(candy([5,4,3,5,6,2]))")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/product-of-array-except-self/description/?envType=study-plan-v2&envId=top-interview-150
4+
//APPROACH 1 :- Complexity This approach has a time complexity of O(n)O(n)O(n) and a space complexity of O(n)O(n)O(n), where nnn is the length of the input array nums.
5+
func productExceptSelf(_ nums: [Int]) -> [Int] {
6+
var prefix = Array(repeating: 1, count: nums.count)
7+
var suffix = Array(repeating: 1, count: nums.count)
8+
var result = Array(repeating: 0, count: nums.count)
9+
for i in 1 ..< nums.count {
10+
prefix[i] = prefix[i - 1] * nums[i - 1]
11+
}
12+
13+
for i in (0 ..< nums.count - 1).reversed() {
14+
suffix[i] = suffix[i + 1] * nums[i + 1]
15+
}
16+
for i in 0 ..< result.count {
17+
result[i] = prefix[i] * suffix[i]
18+
}
19+
20+
return result
21+
}
22+
print("Product of array elements except self using first approach is :- \(productExceptSelf([1,2,3,4]))")
23+
//APPROACH 2 :- Complexity This approach also has a time complexity of O(n)O(n)O(n) and a space complexity of O(1)O(1)O(1), where nnn is the length of the input array nums. (The output array does not count as extra space for space complexiy analysis)
24+
func productExceptSelfTwo(_ nums: [Int]) -> [Int] {
25+
var result = Array(repeating: 1, count: nums.count)
26+
27+
for i in 1 ..< nums.count {
28+
result[i] = result[i - 1] * nums[i - 1]
29+
}
30+
31+
var suffix = 1
32+
for i in (0 ..< nums.count).reversed() {
33+
result[i] *= suffix
34+
suffix *= nums[i]
35+
}
36+
37+
return result
38+
}
39+
print("Product of array elements except self using second approach is :- \(productExceptSelfTwo([1,2,3,4]))")
40+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/trapping-rain-water/description/?envType=study-plan-v2&envId=top-interview-150
4+
//APPROACH 1 :- TimeComplexity O(n), spaceComplexity O(n)
5+
func trap(_ height: [Int]) -> Int {
6+
var maxLeftArray = Array(repeating:0, count : height.count)
7+
var maxRightArray = Array(repeating:0, count : height.count)
8+
var minLeftRightArray = Array(repeating:0, count : height.count)
9+
var waterTrappedArray = Array(repeating:0, count : height.count)
10+
11+
for i in 1..<height.count {
12+
maxLeftArray[i] = max(height[i - 1], maxLeftArray[i - 1])
13+
}
14+
for i in (0..<height.count - 1).reversed() {
15+
maxRightArray[i] = max(height[i + 1], maxRightArray[i + 1])
16+
}
17+
for i in 0..<height.count {
18+
minLeftRightArray[i] = min(maxLeftArray[i], maxRightArray[i])
19+
}
20+
for i in 0..<height.count {
21+
waterTrappedArray[i] = minLeftRightArray[i] - height[i] > 0 ? minLeftRightArray[i] - height[i] : 0
22+
}
23+
return waterTrappedArray.reduce(0, +)
24+
}
25+
print("Total water filled using approch 1 for elevation of [0,1,0,2,1,0,1,3,2,1,2,1] is : \(trap([0,1,0,2,1,0,1,3,2,1,2,1])) ")
26+
27+
//APPROACH 2 :- TimeComplexity O(n), spaceComplexity O(1) using two pointer approach
28+
func trapApproachTwo(_ height: [Int]) -> Int {
29+
var left = 0, right = height.count - 1, maxLeft = height[left], maxRight = height[right], waterFilled = 0
30+
while left < right {
31+
if maxLeft < maxRight {
32+
left += 1
33+
maxLeft = max(maxLeft, height[left])
34+
waterFilled += maxLeft - height[left]
35+
}
36+
else {
37+
right -= 1
38+
maxRight = max(maxRight, height[right])
39+
waterFilled += maxRight - height[right]
40+
}
41+
}
42+
return waterFilled
43+
}
44+
print("Total water filled using approch 2 for elevation of [0,1,0,2,1,0,1,3,2,1,2,1] is : \(trapApproachTwo([0,1,0,2,1,0,1,3,2,1,2,1])) ")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/jump-game-ii/description/?envType=study-plan-v2&envId=top-interview-150
4+
5+
func jump(_ nums: [Int]) -> Int {
6+
if nums.count <= 1 {
7+
return 0
8+
}
9+
if nums[0] == 0 {
10+
return -1
11+
}
12+
var valueMax = nums[0]
13+
var steps = nums[0]
14+
var jumps = 1
15+
var i = 1
16+
for i in 1..<nums.count {
17+
if i == nums.count - 1 { return jumps }
18+
valueMax = max(valueMax , i + nums[i])
19+
steps -= 1
20+
if (steps == 0) {
21+
jumps += 1
22+
if i >= valueMax {
23+
return -1
24+
}
25+
steps = valueMax - i
26+
}
27+
}
28+
return -1
29+
}
30+
print("Minimum jumps required for array [2,3,1,1,4] is :- \(jump([2,3,1,1,4]))")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

DataStrucutureQuestions/Array/BuySellProblem.playground/Contents.swift

Lines changed: 0 additions & 14 deletions
This file was deleted.

DataStrucutureQuestions/Array/BuySellProblem.playground/timeline.xctimeline

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/integer-to-roman/
4+
//TimeComplexity : O(n)
5+
6+
func intToRoman(_ num: Int) -> String {
7+
let arrayOfRomanKeys = [["M": 1000], ["CM": 900], ["D": 500], ["CD": 400],
8+
["C": 100], ["XC": 90], ["L": 50], ["XL": 40], ["X": 10],
9+
["IX": 9], ["V": 5], ["IV": 4], ["I": 1]]
10+
11+
var output = ""
12+
var num = num
13+
for (_, dictionary) in arrayOfRomanKeys.enumerated() {
14+
output += String(repeating: dictionary.keys.first!, count: num / dictionary.values.first!)
15+
if num / dictionary.values.first! != 0 {
16+
num -= dictionary.values.first! * (num / dictionary.values.first!)
17+
}
18+
}
19+
20+
return output
21+
}
22+
print("Interger to Roman conversion of 3 = \(intToRoman(3))")
23+
print("Interger to Roman conversion of 58 = \(intToRoman(58))")
24+
print("Interger to Roman conversion of 1994 = \(intToRoman(1994))")
25+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/roman-to-integer/description/?envType=study-plan-v2&envId=top-interview-150
4+
5+
func romanToInt(_ s: String) -> Int {
6+
var romanToInt : [Character : Int] = [ "I": 1,
7+
"V": 5,
8+
"X": 10,
9+
"L": 50,
10+
"C": 100,
11+
"D": 500,
12+
"M": 1000]
13+
var integerNumber = 0
14+
for i in 0..<s.count-1 {
15+
let currentCharacter = s[s.index(s.startIndex, offsetBy: i)]
16+
let nextCharacter = s[s.index(s.startIndex, offsetBy: i + 1)]
17+
if romanToInt[currentCharacter]! >= romanToInt[nextCharacter]! {
18+
integerNumber += romanToInt[currentCharacter]!
19+
}
20+
else {
21+
integerNumber -= romanToInt[currentCharacter]!
22+
}
23+
}
24+
integerNumber += romanToInt[s.last!]!
25+
return integerNumber
26+
}
27+
print("Roman to integer conversion of III is :- \(romanToInt("III"))")
28+
print("Roman to integer conversion of LVIII is :- \(romanToInt("LVIII"))")
29+
print("Roman to integer conversion of MCMXCIV is :- \(romanToInt("MCMXCIV"))")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/reverse-words-in-a-string/?envType=study-plan-v2&envId=top-interview-150
4+
// - Complexity:
5+
// - time: O(n), where n is the number of words in the input string.
6+
// - space: O(m), where m is the length of the input string.
7+
8+
func reverseWords(_ s: String) -> String {
9+
var arrayFromString = s.split(separator: " ")
10+
var startIndex = 0
11+
var endIndex = arrayFromString.count - 1
12+
13+
while startIndex < endIndex {
14+
arrayFromString.swapAt(startIndex, endIndex)
15+
startIndex += 1
16+
endIndex -= 1
17+
}
18+
return arrayFromString.joined(separator: " ")
19+
}
20+
print("Reverse of the sky is blue is : \(reverseWords("the sky is blue"))")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import UIKit
2+
3+
//https://leetcode.com/problems/length-of-last-word/?envType=study-plan-v2&envId=top-interview-150
4+
//timeComplexity : O(n), spaceComplexity : O(1)
5+
6+
func lengthOfLastWord(_ s: String) -> Int {
7+
// var lastWord = s.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
8+
// return lastWord.last?.count ?? 0
9+
var countOfLastWord = 0
10+
for character in s.reversed() {
11+
if character != " " {
12+
countOfLastWord += 1
13+
} else if countOfLastWord > 0 {
14+
return countOfLastWord
15+
}
16+
}
17+
return countOfLastWord
18+
}
19+
20+
print("Length of Last word of Hello World is :- \(lengthOfLastWord("Hello World"))")
21+
print("Length of Last word of fly me to the moon is :- \(lengthOfLastWord(" fly me to the moon "))")
22+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)