Skip to content

Commit cc4ca68

Browse files
committed
Added tasks 1-39
1 parent c86902d commit cc4ca68

File tree

27 files changed

+3766
-2
lines changed

27 files changed

+3766
-2
lines changed

README.md

+1,274-2
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 1\. Two Sum
5+
6+
Easy
7+
8+
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
9+
10+
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
11+
12+
You can return the answer in any order.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,7,11,15], target = 9
17+
18+
**Output:** [0,1]
19+
20+
**Explanation:** Because nums[0] + nums[1] == 9, we return [0, 1].
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [3,2,4], target = 6
25+
26+
**Output:** [1,2]
27+
28+
**Example 3:**
29+
30+
**Input:** nums = [3,3], target = 6
31+
32+
**Output:** [0,1]
33+
34+
**Constraints:**
35+
36+
* <code>2 <= nums.length <= 10<sup>4</sup></code>
37+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
38+
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
39+
* **Only one valid answer exists.**
40+
41+
**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code> time complexity?
42+
43+
To solve the "Two Sum" problem in Swift using a `Solution` class, follow these steps:
44+
45+
1. **Understand the problem:** You need to find two indices in the array `nums` such that the numbers at those indices add up to `target`. Each input has exactly one solution, and the same element cannot be used twice.
46+
47+
2. **Plan your approach:**
48+
- Use a dictionary to store the difference between the target and each number in the array. This dictionary will help in checking if the complement of the current number (i.e., `target - nums[i]`) has been seen before.
49+
- Iterate through the array, and for each element, check if it exists in the dictionary.
50+
- If it exists, return the indices of the current element and the stored element.
51+
- If it does not exist, add the element and its index to the dictionary.
52+
53+
3. **Implement the solution:**
54+
- Define the `Solution` class and the `twoSum` method.
55+
- Use a dictionary to keep track of the numbers and their indices.
56+
- Iterate through the array and perform the necessary checks and updates.
57+
58+
Here is the Swift implementation of the solution:
59+
60+
```swift
61+
class Solution {
62+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
63+
// Create a dictionary to store the number and its index
64+
var numDict = [Int: Int]()
65+
66+
// Iterate through the nums array
67+
for (index, num) in nums.enumerated() {
68+
// Calculate the complement
69+
let complement = target - num
70+
71+
// Check if the complement exists in the dictionary
72+
if let complementIndex = numDict[complement] {
73+
// If found, return the indices
74+
return [complementIndex, index]
75+
}
76+
77+
// Otherwise, add the current number and its index to the dictionary
78+
numDict[num] = index
79+
}
80+
81+
// In case no solution is found (which shouldn't happen as per problem constraints)
82+
return []
83+
}
84+
}
85+
86+
// Example usage:
87+
let solution = Solution()
88+
let nums1 = [2, 7, 11, 15]
89+
let target1 = 9
90+
print(solution.twoSum(nums1, target1)) // Output: [0, 1]
91+
92+
let nums2 = [3, 2, 4]
93+
let target2 = 6
94+
print(solution.twoSum(nums2, target2)) // Output: [1, 2]
95+
96+
let nums3 = [3, 3]
97+
let target3 = 6
98+
print(solution.twoSum(nums3, target3)) // Output: [0, 1]
99+
```
100+
101+
### Explanation:
102+
- **Dictionary (`numDict`):** This dictionary keeps track of each number and its index as we iterate through the array.
103+
- **Iteration:** For each number in the array, calculate the complement (`target - num`).
104+
- **Check:** If the complement is already in the dictionary, return the indices of the complement and the current number.
105+
- **Update:** If not, add the current number and its index to the dictionary and continue.
106+
107+
This approach ensures that the solution has a time complexity of \(O(n)\), which is efficient for large input sizes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 2\. Add Two Numbers
5+
6+
Medium
7+
8+
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
9+
10+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg)
15+
16+
**Input:** l1 = [2,4,3], l2 = [5,6,4]
17+
18+
**Output:** [7,0,8]
19+
20+
**Explanation:** 342 + 465 = 807.
21+
22+
**Example 2:**
23+
24+
**Input:** l1 = [0], l2 = [0]
25+
26+
**Output:** [0]
27+
28+
**Example 3:**
29+
30+
**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
31+
32+
**Output:** [8,9,9,9,0,0,0,1]
33+
34+
**Constraints:**
35+
36+
* The number of nodes in each linked list is in the range `[1, 100]`.
37+
* `0 <= Node.val <= 9`
38+
* It is guaranteed that the list represents a number that does not have leading zeros.
39+
40+
To solve the Add Two Numbers problem in Swift using a `Solution` class, we'll follow these steps:
41+
42+
1. Define a `ListNode` class to represent nodes in a linked list.
43+
2. Define a `Solution` class with a method named `addTwoNumbers`.
44+
3. Inside the `addTwoNumbers` method, traverse both input linked lists simultaneously:
45+
- Keep track of a carry variable to handle cases where the sum of two digits exceeds 9.
46+
- Calculate the sum of the current nodes' values along with the carry.
47+
- Update the carry for the next iteration.
48+
- Create a new node with the sum % 10 and attach it to the result linked list.
49+
- Move to the next nodes in both input lists.
50+
4. After finishing the traversal, check if there is any remaining carry. If so, add a new node with the carry to the result.
51+
5. Return the head of the result linked list.
52+
53+
Here's the implementation:
54+
55+
```swift
56+
/*
57+
* Definition for singly-linked list.
58+
* public class ListNode {
59+
* public var val: Int
60+
* public var next: ListNode?
61+
* public init() { self.val = 0; self.next = nil; }
62+
* public init(_ val: Int) { self.val = val; self.next = nil; }
63+
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
64+
* }
65+
*/
66+
class Solution {
67+
68+
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
69+
return addNumbers(l1, l2, 0)
70+
}
71+
72+
func addNumbers(_ l1: ListNode?, _ l2: ListNode?, _ carryOver: Int) -> ListNode? {
73+
guard !(l1 == nil && l2 == nil && carryOver == 0 ) else { return nil }
74+
let sum = ( l1?.val ?? 0 ) + ( l2?.val ?? 0 ) + carryOver
75+
let carryOver = sum / 10
76+
let value = sum % 10
77+
return ListNode(value, addNumbers(l1?.next, l2?.next, carryOver))
78+
}
79+
}
80+
```
81+
82+
This implementation provides a solution to the Add Two Numbers problem using linked lists in Swift.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 3\. Longest Substring Without Repeating Characters
5+
6+
Medium
7+
8+
Given a string `s`, find the length of the **longest substring** without repeating characters.
9+
10+
**Example 1:**
11+
12+
**Input:** s = "abcabcbb"
13+
14+
**Output:** 3
15+
16+
**Explanation:** The answer is "abc", with the length of 3.
17+
18+
**Example 2:**
19+
20+
**Input:** s = "bbbbb"
21+
22+
**Output:** 1
23+
24+
**Explanation:** The answer is "b", with the length of 1.
25+
26+
**Example 3:**
27+
28+
**Input:** s = "pwwkew"
29+
30+
**Output:** 3
31+
32+
**Explanation:** The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
33+
34+
**Example 4:**
35+
36+
**Input:** s = ""
37+
38+
**Output:** 0
39+
40+
**Constraints:**
41+
42+
* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
43+
* `s` consists of English letters, digits, symbols and spaces.
44+
45+
To solve the Longest Substring Without Repeating Characters problem in Swift using a `Solution` class, we'll follow these steps:
46+
47+
1. Define a `Solution` class with a method named `lengthOfLongestSubstring`.
48+
2. Initialize variables to keep track of the starting index of the substring (`start`), the maximum length (`maxLen`), and a hashmap to store characters and their indices.
49+
3. Iterate through the string `s`, and for each character:
50+
- Check if the character exists in the hashmap and its index is greater than or equal to the `start` index.
51+
- If found, update the `start` index to the index after the last occurrence of the character.
52+
- Update the maximum length if necessary.
53+
- Update the index of the current character in the hashmap.
54+
4. Return the maximum length found.
55+
5. Handle the edge case where the input string is empty.
56+
57+
Here's the implementation:
58+
59+
```swift
60+
public class Solution {
61+
public func lengthOfLongestSubstring(_ s: String) -> Int {
62+
var lastIndices = Array(repeating: -1, count: 256)
63+
var maxLen = 0
64+
var curLen = 0
65+
var start = 0
66+
67+
for (i, char) in s.enumerated() {
68+
let asciiValue = Int(char.asciiValue!)
69+
if lastIndices[asciiValue] < start {
70+
lastIndices[asciiValue] = i
71+
curLen += 1
72+
} else {
73+
let lastIndex = lastIndices[asciiValue]
74+
start = lastIndex + 1
75+
curLen = i - start + 1
76+
lastIndices[asciiValue] = i
77+
}
78+
if curLen > maxLen {
79+
maxLen = curLen
80+
}
81+
}
82+
return maxLen
83+
}
84+
}
85+
```
86+
87+
This implementation provides a solution to the Longest Substring Without Repeating Characters problem in Swift.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 4\. Median of Two Sorted Arrays
5+
6+
Hard
7+
8+
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
9+
10+
The overall run time complexity should be `O(log (m+n))`.
11+
12+
**Example 1:**
13+
14+
**Input:** nums1 = [1,3], nums2 = [2]
15+
16+
**Output:** 2.00000
17+
18+
**Explanation:** merged array = [1,2,3] and median is 2.
19+
20+
**Example 2:**
21+
22+
**Input:** nums1 = [1,2], nums2 = [3,4]
23+
24+
**Output:** 2.50000
25+
26+
**Explanation:** merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
27+
28+
**Example 3:**
29+
30+
**Input:** nums1 = [0,0], nums2 = [0,0]
31+
32+
**Output:** 0.00000
33+
34+
**Example 4:**
35+
36+
**Input:** nums1 = [], nums2 = [1]
37+
38+
**Output:** 1.00000
39+
40+
**Example 5:**
41+
42+
**Input:** nums1 = [2], nums2 = []
43+
44+
**Output:** 2.00000
45+
46+
**Constraints:**
47+
48+
* `nums1.length == m`
49+
* `nums2.length == n`
50+
* `0 <= m <= 1000`
51+
* `0 <= n <= 1000`
52+
* `1 <= m + n <= 2000`
53+
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>
54+
55+
To solve the Median of Two Sorted Arrays problem in Swift using a `Solution` class, we'll follow these steps:
56+
57+
1. Define a `Solution` class with a method named `findMedianSortedArrays`.
58+
2. Calculate the total length of the combined array (m + n).
59+
3. Determine the middle index or indices of the combined array based on its length (for both even and odd lengths).
60+
4. Implement a binary search algorithm to find the correct position for partitioning the two arrays such that elements to the left are less than or equal to elements on the right.
61+
5. Calculate the median based on the partitioned arrays.
62+
6. Handle edge cases where one or both arrays are empty or where the combined length is odd or even.
63+
7. Return the calculated median.
64+
65+
Here's the implementation:
66+
67+
```swift
68+
public class Solution {
69+
public func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
70+
let n1 = nums1.count
71+
let n2 = nums2.count
72+
73+
if n1 > n2 {
74+
return findMedianSortedArrays(nums2, nums1)
75+
}
76+
77+
var low = 0
78+
var high = n1
79+
80+
while low <= high {
81+
let cut1 = (low + high) / 2
82+
let cut2 = (n1 + n2 + 1) / 2 - cut1
83+
84+
let l1 = cut1 == 0 ? Int.min : nums1[cut1 - 1]
85+
let l2 = cut2 == 0 ? Int.min : nums2[cut2 - 1]
86+
let r1 = cut1 == n1 ? Int.max : nums1[cut1]
87+
let r2 = cut2 == n2 ? Int.max : nums2[cut2]
88+
89+
if l1 <= r2 && l2 <= r1 {
90+
if (n1 + n2) % 2 == 0 {
91+
return (Double(max(l1, l2)) + Double(min(r1, r2))) / 2.0
92+
} else {
93+
return Double(max(l1, l2))
94+
}
95+
} else if l1 > r2 {
96+
high = cut1 - 1
97+
} else {
98+
low = cut1 + 1
99+
}
100+
}
101+
102+
return 0.0
103+
}
104+
}
105+
```
106+
107+
This implementation provides a solution to the Median of Two Sorted Arrays problem in Swift with a runtime complexity of O(log(min(m, n))).

0 commit comments

Comments
 (0)