├── .gitignore
├── LICENSE
├── README.md
└── Solutions
├── Solutions-Bridging-Header.h
├── Solutions.xcodeproj
├── project.pbxproj
└── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── Solutions
├── AppDelegate.swift
├── Base.lproj
│ ├── LaunchScreen.xib
│ └── Main.storyboard
├── Easy
│ ├── Easy_006_ZigZag_Conversion.swift
│ ├── Easy_007_Reverse_Integer.swift
│ ├── Easy_008_String_to_Integer_atoi.swift
│ ├── Easy_009_Palindrome_Number.swift
│ ├── Easy_013_Roman_To_Integer.swift
│ ├── Easy_014_Longest_Common_Prefix.swift
│ ├── Easy_019_Remove_Nth_Node_From_End_Of_List.swift
│ ├── Easy_020_Valid_Parentheses.swift
│ ├── Easy_021_Merge_Two_Sorted_Lists.swift
│ ├── Easy_026_Remove_Duplicates_from_Sorted_Array.swift
│ ├── Easy_027_Remove_Element.swift
│ ├── Easy_028_Implement_StrStr.swift
│ ├── Easy_036_Valid_Sudoku.swift
│ ├── Easy_038_Count_And_Say.swift
│ ├── Easy_058_Length_Of_Last_Word.swift
│ ├── Easy_066_Plus_One.swift
│ ├── Easy_067_Add_Binary.swift
│ ├── Easy_070_Climbing_Stairs.swift
│ ├── Easy_083_Remove_Duplicates_From_Sorted_List.swift
│ ├── Easy_088_Merge_Sorted_Array.swift
│ ├── Easy_100_Same_Tree.swift
│ ├── Easy_101_Symmetric_Tree.swift
│ └── Easy_102_Binary_Tree_Level_Order_Traversal.swift
├── Hard
│ ├── Hard_004_Median_Of_Two_Sorted_Arrays.swift
│ ├── Hard_010_Regular_Expression_Matching.swift
│ ├── Hard_023_Merge_K_Sorted_Lists.swift
│ ├── Hard_025_Reverse_Nodes_In_K_Group.swift
│ ├── Hard_030_Substring_With_Concatenation_Of_All_Words.swift
│ ├── Hard_032_Longest_Valid_Parentheses.swift
│ ├── Hard_033_Search_In_Rotated_Sorted_Array.swift
│ ├── Hard_037_Sudoku_Solver.swift
│ ├── Hard_041_First_Missing_Positive.swift
│ ├── Hard_042_Trapping_Rain_Water.swift
│ ├── Hard_044_Wildcard_Matching.swift
│ ├── Hard_045_Jump_Game_II.swift
│ ├── Hard_047_Permutations_II.swift
│ ├── Hard_051_N_Queens.swift
│ ├── Hard_052_N_Queens_II.swift
│ ├── Hard_056_Merge_Intervals.swift
│ ├── Hard_057_Insert_Interval.swift
│ ├── Hard_065_Valid_Number.swift
│ ├── Hard_068_Text_Justification.swift
│ ├── Hard_072_Edit_Distance.swift
│ ├── Hard_076_Minimum_Window_Substring.swift
│ ├── Hard_084_Largest_Rectangle_In_Histogram.swift
│ ├── Hard_085_Maximal_Rectangle.swift
│ ├── Hard_087_Scramble_String.swift
│ ├── Hard_097_Interleaving_String.swift
│ └── Hard_099_Recover_Binary_Search_Tree.swift
├── Images.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
├── Info.plist
├── Medium
│ ├── Medium_001_Two_Sum.swift
│ ├── Medium_002_Add_Two_Numbers.swift
│ ├── Medium_003_Longest_Substring_Without_Repeating_Characters.swift
│ ├── Medium_005_Longest_Palindromic_Substring.swift
│ ├── Medium_011_Container_With_Most_Water.swift
│ ├── Medium_012_Integer_To_Roman.swift
│ ├── Medium_015_3Sum.swift
│ ├── Medium_016_3Sum_Closest.swift
│ ├── Medium_017_Letter_Combinations_Of_A_Phone_Number.swift
│ ├── Medium_018_4Sum.swift
│ ├── Medium_022_Generate_Parentheses.swift
│ ├── Medium_024_Swap_Nodes_In_Pairs.swift
│ ├── Medium_029_Divide_Two_Integers.swift
│ ├── Medium_031_Next_Permutation.swift
│ ├── Medium_034_Search_For_A_Range.swift
│ ├── Medium_035_Search_Insert_Position.swift
│ ├── Medium_039_Combination_Sum.swift
│ ├── Medium_040_Combination_Sum_II.swift
│ ├── Medium_043_Multiply_Strings.swift
│ ├── Medium_046_Permutations.swift
│ ├── Medium_048_Rotate_Image.swift
│ ├── Medium_049_Anagrams.swift
│ ├── Medium_050_Pow_X_N.swift
│ ├── Medium_053_Maximum_Subarray.swift
│ ├── Medium_054_Spiral_Matrix.swift
│ ├── Medium_055_Jump_Game.swift
│ ├── Medium_059_Spiral_Matrix_II.swift
│ ├── Medium_060_Permutation_Sequence.swift
│ ├── Medium_061_Rotate_List.swift
│ ├── Medium_062_Unique_Paths.swift
│ ├── Medium_063_Unique_Paths_II.swift
│ ├── Medium_064_Minimum_Path_Sum.swift
│ ├── Medium_069_Sqrt_X.swift
│ ├── Medium_071_Simplify_Path.swift
│ ├── Medium_073_Set_Matrix_Zeroes.swift
│ ├── Medium_074_Search_A_2D_Matrix.swift
│ ├── Medium_075_Sort_Colors.swift
│ ├── Medium_077_Combinations.swift
│ ├── Medium_078_Subsets.swift
│ ├── Medium_079_Word_Search.swift
│ ├── Medium_080_Remove_Duplicates_From_Sorted_Array_II.swift
│ ├── Medium_081_Search_In_Rotated_Sorted_Array_II.swift
│ ├── Medium_082_Remove_Duplicates_From_Sorted_List_II.swift
│ ├── Medium_086_Partition_List.swift
│ ├── Medium_089_Gray_Code.swift
│ ├── Medium_090_Subsets_II.swift
│ ├── Medium_091_Decode_Ways.swift
│ ├── Medium_092_Reverse_Linked_List_II.swift
│ ├── Medium_093_Restore_IP_Addresses.swift
│ ├── Medium_094_Binary_Tree_Inorder_Traversal.swift
│ ├── Medium_095_Unique_Binary_Search_Trees_II.swift
│ ├── Medium_096_Unique_Binary_Search_Trees.swift
│ └── Medium_098_Validate_Binary_Search_Tree.swift
└── ViewController.swift
├── SolutionsTests-Bridging-Header.h
├── SolutionsTests
├── Easy
│ ├── Easy_006_ZigZag_Conversion_Test.swift
│ ├── Easy_007_Reverse_Integer_Test.swift
│ ├── Easy_008_String_to_Integer_atoi_Test.swift
│ ├── Easy_009_Palindrome_Number_Test.swift
│ ├── Easy_013_Roman_To_Integer_Test.swift
│ ├── Easy_014_Longest_Common_Prefix_Test.swift
│ ├── Easy_019_Remove_Nth_Node_From_End_Of_List_Test.swift
│ ├── Easy_020_Valid_Parentheses_Test.swift
│ ├── Easy_021_Merge_Two_Sorted_Lists_Test.swift
│ ├── Easy_026_Remove_Duplicates_from_Sorted_Array_Test.swift
│ ├── Easy_027_Remove_Element_Test.swift
│ ├── Easy_028_Implement_StrStr_Test.swift
│ ├── Easy_036_Valid_Sudoku_Test.swift
│ ├── Easy_038_Count_And_Say_Test.swift
│ ├── Easy_058_Length_Of_Last_Word_Test.swift
│ ├── Easy_066_Plus_One_Test.swift
│ ├── Easy_067_Add_Binary_Test.swift
│ ├── Easy_070_Climbing_Stairs_Test.swift
│ ├── Easy_083_Remove_Duplicates_From_Sorted_List_Test.swift
│ ├── Easy_088_Merge_Sorted_Array_Test.swift
│ ├── Easy_100_Same_Tree_Test.swift
│ ├── Easy_101_Symmetric_Tree_Test.swift
│ └── Easy_102_Binary_Tree_Level_Order_Traversal_Test.swift
├── Hard
│ ├── Hard_004_Median_Of_Two_Sorted_Arrays_Test.swift
│ ├── Hard_010_Regular_Expression_Matching_Test.swift
│ ├── Hard_023_Merge_K_Sorted_Lists_Test.swift
│ ├── Hard_025_Reverse_Nodes_In_K_Group_Test.swift
│ ├── Hard_030_Substring_With_Concatenation_Of_All_Words_Test.swift
│ ├── Hard_032_Longest_Valid_Parentheses_Test.swift
│ ├── Hard_033_Search_In_Rotated_Sorted_Array_Test.swift
│ ├── Hard_037_Sudoku_Solver_Test.swift
│ ├── Hard_041_First_Missing_Positive_Test.swift
│ ├── Hard_042_Trapping_Rain_Water_Test.swift
│ ├── Hard_044_Wildcard_Matching_Test.swift
│ ├── Hard_045_Jump_Game_II_Test.swift
│ ├── Hard_047_Permutations_II_Test.swift
│ ├── Hard_051_N_Queens_Test.swift
│ ├── Hard_052_N_Queens_II_Test.swift
│ ├── Hard_056_Merge_Intervals_Test.swift
│ ├── Hard_057_Insert_Interval_Test.swift
│ ├── Hard_065_Valid_Number_Test.swift
│ ├── Hard_068_Text_Justification_Test.swift
│ ├── Hard_072_Edit_Distance_Test.swift
│ ├── Hard_076_Minimum_Window_Substring_Test.swift
│ ├── Hard_084_Largest_Rectangle_In_Histogram_Test.swift
│ ├── Hard_085_Maximal_Rectangle_Test.swift
│ ├── Hard_087_Scramble_String_Test.swift
│ ├── Hard_097_Interleaving_String_Test.swift
│ └── Hard_099_Recover_Binary_Search_Tree_Test.swift
├── Info.plist
├── Medium
│ ├── Medium_001_Two_Sum_Test.swift
│ ├── Medium_002_Add_Two_Numbers_Test.swift
│ ├── Medium_003_Longest_Substring_Without_Repeating_Characters_Test.swift
│ ├── Medium_005_Longest_Palindromic_Substring_Test.swift
│ ├── Medium_011_Container_With_Most_Water_Test.swift
│ ├── Medium_012_Integer_To_Roman_Test.swift
│ ├── Medium_015_3Sum_Test.swift
│ ├── Medium_016_3Sum_Closest_Test.swift
│ ├── Medium_017_Letter_Combinations_Of_A_Phone_Number_Test.swift
│ ├── Medium_018_4Sum_Test.swift
│ ├── Medium_022_Generate_Parentheses_Test.swift
│ ├── Medium_024_Swap_Nodes_In_Pairs_Test.swift
│ ├── Medium_029_Divide_Two_Integers_Test.swift
│ ├── Medium_031_Next_Permutation_Test.swift
│ ├── Medium_034_Search_For_A_Range_Test.swift
│ ├── Medium_035_Search_Insert_Position_Test.swift
│ ├── Medium_039_Combination_Sum_Test.swift
│ ├── Medium_040_Combination_Sum_II_Test.swift
│ ├── Medium_043_Multiply_Strings_Test.swift
│ ├── Medium_046_Permutations_Test.swift
│ ├── Medium_048_Rotate_Image_Test.swift
│ ├── Medium_049_Anagrams_Test.swift
│ ├── Medium_050_Pow_X_N_Test.swift
│ ├── Medium_053_Maximum_Subarray_Test.swift
│ ├── Medium_054_Spiral_Matrix_Test.swift
│ ├── Medium_055_Jump_Game_Test.swift
│ ├── Medium_059_Spiral_Matrix_II_Test.swift
│ ├── Medium_060_Permutation_Sequence_Test.swift
│ ├── Medium_061_Rotate_List_Test.swift
│ ├── Medium_062_Unique_Paths_Test.swift
│ ├── Medium_063_Unique_Paths_II_Test.swift
│ ├── Medium_064_Minimum_Path_Sum_Test.swift
│ ├── Medium_069_Sqrt_X_Test.swift
│ ├── Medium_071_Simplify_Path_Test.swift
│ ├── Medium_073_Set_Matrix_Zeroes_Test.swift
│ ├── Medium_074_Search_A_2D_Matrix_Test.swift
│ ├── Medium_075_Sort_Colors_Test.swift
│ ├── Medium_077_Combinations_Test.swift
│ ├── Medium_078_Subsets_Test.swift
│ ├── Medium_079_Word_Search_Test.swift
│ ├── Medium_080_Remove_Duplicates_From_Sorted_Array_II_Test.swift
│ ├── Medium_081_Search_In_Rotated_Sorted_Array_II_Test.swift
│ ├── Medium_082_Remove_Duplicates_From_Sorted_List_II_Test.swift
│ ├── Medium_086_Partition_List_Test.swift
│ ├── Medium_089_Gray_Code_Test.swift
│ ├── Medium_090_Subsets_II_Test.swift
│ ├── Medium_091_Decode_Ways_Test.swift
│ ├── Medium_092_Reverse_Linked_List_II_Test.swift
│ ├── Medium_093_Restore_IP_Addresses_Test.swift
│ ├── Medium_094_Binary_Tree_Inorder_Traversal_Test.swift
│ ├── Medium_095_Unique_Binary_Search_Trees_II_Test.swift
│ ├── Medium_096_Unique_Binary_Search_Trees_Test.swift
│ └── Medium_098_Validate_Binary_Search_Tree_Test.swift
└── SolutionsTestsHelper.swift
└── Solutions_ObjC
├── Easy
├── ObjC_Easy_100_Same_Tree.h
├── ObjC_Easy_100_Same_Tree.m
├── ObjC_Easy_101_Symmetric_Tree.h
└── ObjC_Easy_101_Symmetric_Tree.m
├── Hard
├── ObjC_Hard_004_Median_Of_Two_Sorted_Arrays.h
├── ObjC_Hard_004_Median_Of_Two_Sorted_Arrays.m
├── ObjC_Hard_097_Interleaving_String.h
├── ObjC_Hard_097_Interleaving_String.m
├── ObjC_Hard_099_Recover_Binary_Search_Tree.h
└── ObjC_Hard_099_Recover_Binary_Search_Tree.m
└── Medium
├── ObjC_Medium_001_Two_Sum.h
├── ObjC_Medium_001_Two_Sum.m
├── ObjC_Medium_002_Add_Two_Numbers.h
├── ObjC_Medium_002_Add_Two_Numbers.m
├── ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters.h
├── ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters.m
├── ObjC_Medium_005_Longest_Palindromic_Substring.h
├── ObjC_Medium_005_Longest_Palindromic_Substring.m
├── ObjC_Medium_017_Letter_Combinations_Of_A_Phone_Number.h
├── ObjC_Medium_017_Letter_Combinations_Of_A_Phone_Number.m
├── ObjC_Medium_092_Reverse_Linked_List_II.h
├── ObjC_Medium_092_Reverse_Linked_List_II.m
├── ObjC_Medium_093_Restore_IP_Addresses.h
├── ObjC_Medium_093_Restore_IP_Addresses.m
├── ObjC_Medium_094_Binary_Tree_Inorder_Traversal.h
├── ObjC_Medium_094_Binary_Tree_Inorder_Traversal.m
├── ObjC_Medium_095_Unique_Binary_Search_Trees_II.h
├── ObjC_Medium_095_Unique_Binary_Search_Trees_II.m
├── ObjC_Medium_096_Unique_Binary_Search_Trees.h
├── ObjC_Medium_096_Unique_Binary_Search_Trees.m
├── ObjC_Medium_098_Validate_Binary_Search_Tree.h
└── ObjC_Medium_098_Validate_Binary_Search_Tree.m
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 |
3 | # Created by https://www.gitignore.io
4 |
5 | ### Swift ###
6 | # Xcode
7 | #
8 | build/
9 | *.pbxuser
10 | !default.pbxuser
11 | *.mode1v3
12 | !default.mode1v3
13 | *.mode2v3
14 | !default.mode2v3
15 | *.perspectivev3
16 | !default.perspectivev3
17 | xcuserdata
18 | *.xccheckout
19 | *.moved-aside
20 | DerivedData
21 | *.hmap
22 | *.ipa
23 | *.xcuserstate
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015 Di Wu
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
--------------------------------------------------------------------------------
/Solutions/Solutions-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | //
2 | // Use this file to import your target's public headers that you would like to expose to Swift.
3 | //
4 |
5 |
--------------------------------------------------------------------------------
/Solutions/Solutions.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Solutions/Solutions/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 3/6/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | @UIApplicationMain
12 | class AppDelegate: UIResponder, UIApplicationDelegate {
13 |
14 | var window: UIWindow?
15 |
16 |
17 | @nonobjc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
18 | // Override point for customization after application launch.
19 | return true
20 | }
21 |
22 | func applicationWillResignActive(_ application: UIApplication) {
23 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
24 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
25 | }
26 |
27 | func applicationDidEnterBackground(_ application: UIApplication) {
28 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
29 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
30 | }
31 |
32 | func applicationWillEnterForeground(_ application: UIApplication) {
33 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
34 | }
35 |
36 | func applicationDidBecomeActive(_ application: UIApplication) {
37 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
38 | }
39 |
40 | func applicationWillTerminate(_ application: UIApplication) {
41 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
42 | }
43 |
44 |
45 | }
46 |
47 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_009_Palindrome_Number.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://oj.leetcode.com/problems/palindrome-number/
4 |
5 | #9 Palindrome Number
6 |
7 | Level: easy
8 |
9 | Determine whether an integer is a palindrome. Do this without extra space.
10 |
11 | Some hints:
12 |
13 | Could negative integers be palindromes? (ie, -1)
14 |
15 | If you are thinking of converting the integer to string, note the restriction of using extra space.
16 |
17 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
18 |
19 | There is a more generic way of solving this problem.
20 |
21 | Inspired by @hln9319 https://leetcode.com/discuss/12693/neat-ac-java-code-o-n-time-complexity
22 |
23 | */
24 |
25 | struct Easy_009_Palindrome_Number {
26 | // O (N)
27 | static func isPalindrome(_ x: Int) -> Bool {
28 | guard x != Int.min else {
29 | return false;
30 | }
31 | var tmp = abs(x)
32 | let reference = abs(x)
33 | var candidate = 0
34 | while tmp > 0 {
35 | if candidate > Int.max / 10 {
36 | return false
37 | }
38 | candidate = candidate * 10 + tmp % 10
39 | tmp = tmp / 10
40 | }
41 | return (candidate == reference)
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_013_Roman_To_Integer.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/roman-to-integer/
4 |
5 | #13 Roman To Integer
6 |
7 | Level: easy
8 |
9 | Given a roman numeral, convert it to an integer.
10 |
11 | Input is guaranteed to be within the range from 1 to 3999.
12 |
13 | Inspired by @makeittrue at https://leetcode.com/discuss/2369/solution-for-this-question-but-dont-know-there-any-easier-way
14 |
15 | */
16 |
17 | private extension String {
18 | subscript (index: Int) -> Character {
19 | return self[self.index(self.startIndex, offsetBy: index)]
20 | }
21 | }
22 |
23 | class Easy_013_Roman_To_Integer {
24 | // O (N)
25 | // One pass
26 | class func romanToInt(s: String) -> Int {
27 | var result: Int = 0
28 | let length: Int = s.count
29 | for i in (0...length-1).reversed() {
30 | let c: Character = s[i]
31 | switch c {
32 | case "I":
33 | result += result >= 5 ? -1 : 1
34 | case "V":
35 | result += 5
36 | case "X":
37 | result += 10 * (result >= 50 ? -1 : 1)
38 | case "L":
39 | result += 50
40 | case "C":
41 | result += 100 * (result >= 500 ? -1 : 1)
42 | case "D":
43 | result += 500
44 | case "M":
45 | result += 1000
46 | default:
47 | break
48 | }
49 | }
50 | return result
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_014_Longest_Common_Prefix.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/longest-common-prefix/
4 |
5 | #14 Longest Common Prefix
6 |
7 | Level: easy
8 |
9 | Write a function to find the longest common prefix string amongst an array of strings.
10 |
11 | Inspired by @garysui at https://leetcode.com/discuss/15755/optimal-solution
12 |
13 | */
14 |
15 | private extension String {
16 | subscript(intIndex: Int) -> Character {
17 | let index = self.index(self.startIndex, offsetBy: intIndex)
18 | return self[index]
19 | }
20 | subscript(range: Range) -> String {
21 | let lowerBoundIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
22 | let upperBoundIndex = self.index(self.startIndex, offsetBy: range.upperBound)
23 | let rangeInStringIndex = lowerBoundIndex ..< upperBoundIndex
24 | let stringSlice = self[rangeInStringIndex]
25 | return String(stringSlice)
26 | }
27 | }
28 |
29 | struct Easy_014_Longest_Common_Prefix {
30 | // t = O(N*M), s = O(1)
31 | static func longestCommonPrefix(_ input: [String]?) -> String {
32 | guard let arr = input else {
33 | return ""
34 | }
35 | guard arr.count > 0 else {
36 | return ""
37 | }
38 | let len = arr[0].count
39 | let arrLen = arr.count
40 | for i in 0 ..< len {
41 | let char = arr[0][i]
42 | for j in 1 ..< arrLen {
43 | if i == arr[j].count || char != arr[j][i] {
44 | return arr[0][0 ..< i]
45 | }
46 | }
47 | }
48 | return arr[0]
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_019_Remove_Nth_Node_From_End_Of_List.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://github.com/diwu/LeetCode-Solutions-in-Swift
4 |
5 | #19 Remove Nth Node From End of List
6 |
7 | Level: easy
8 |
9 | Given a linked list, remove the nth node from the end of list and return its head.
10 |
11 | For example,
12 |
13 | Given linked list: 1->2->3->4->5, and n = 2.
14 |
15 | After removing the second node from the end, the linked list becomes 1->2->3->5.
16 |
17 | Note:
18 |
19 | Given n will always be valid.
20 | Try to do this in one pass.
21 |
22 | Inspired by @i at https://leetcode.com/discuss/1656/is-there-a-solution-with-one-pass-and-o-1-space
23 |
24 | */
25 |
26 | class Easy_019_Remove_Nth_Node_From_End_Of_List {
27 |
28 | class Node {
29 | var value: Int
30 | var next: Node?
31 | init(value: Int, next: Node?) {
32 | self.value = value
33 | self.next = next
34 | }
35 | }
36 |
37 | class func removeNthFromEnd(_ head: Node?, n: Int) -> Node? {
38 | let dummyHead: Node = Node(value: 0, next: head)
39 | var fast: Node? = dummyHead, slow: Node? = dummyHead
40 | var localN = n
41 | while localN > 0 {
42 | fast = fast?.next
43 | localN -= 1
44 | }
45 | while fast?.next != nil {
46 | fast = fast?.next
47 | slow = slow?.next
48 | }
49 | slow?.next = slow?.next?.next
50 | return dummyHead.next
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_020_Valid_Parentheses.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/valid-parentheses/
4 |
5 | #20 Valid_Parentheses
6 |
7 | Level: easy
8 |
9 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
10 |
11 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
12 |
13 | Inspired by @exodia at https://leetcode.com/discuss/21440/sharing-my-simple-cpp-code-with-2ms
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | private extension String {
20 | func randomAccessCharacterArray() -> Array {
21 | return Array(self)
22 | }
23 | }
24 |
25 | struct Easy_020_Valid_Parentheses {
26 | // t=O(N), s=O(N)
27 | static func isValid(_ s: String) -> Bool {
28 | let charArr = s.randomAccessCharacterArray()
29 | let dict: Dictionary = [
30 | "}":"{",
31 | "]":"[",
32 | ")":"("
33 | ]
34 | var stack: Array = []
35 | for char in charArr {
36 | if char == "}" || char == ")" || char == "]" {
37 | if stack.isEmpty || stack.last != dict[char] {
38 | return false
39 | } else {
40 | stack.removeLast()
41 | }
42 | } else {
43 | stack.append(char)
44 | }
45 | }
46 | return stack.isEmpty
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_021_Merge_Two_Sorted_Lists.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/merge-two-sorted-lists/
4 |
5 | #21 Merge Two Sorted Lists
6 |
7 | Level: easy
8 |
9 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
10 |
11 | Inspired by @xiaohui7 at https://leetcode.com/discuss/18986/14-line-clean-c-solution
12 |
13 | */
14 |
15 | import Foundation
16 |
17 | class Easy_021_Merge_Two_Sorted_Lists {
18 |
19 | class Node {
20 | var value: Int
21 | var next: Node?
22 | init (value: Int = 0, next: Node? = nil) {
23 | self.value = value
24 | self.next = next
25 | }
26 | }
27 | class func mergeTwoLists(l1 list1: Node?, l2 list2: Node?) -> Node? {
28 | var l1 = list1
29 | var l2 = list2
30 | let dummy: Node = Node()
31 | var cursor: Node? = dummy
32 | while l1 != nil && l2 != nil {
33 | if l1!.value < l2!.value {
34 | cursor?.next = l1
35 | l1 = l1?.next
36 | } else {
37 | cursor?.next = l2
38 | l2 = l2?.next
39 | }
40 | cursor = cursor?.next
41 | }
42 | cursor?.next = l1 != nil ? l1 : l2
43 | return dummy.next
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_026_Remove_Duplicates_from_Sorted_Array.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/
4 |
5 | #26 Remove Duplicates from Sorted Array
6 |
7 | Level: easy
8 |
9 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
10 |
11 | Do not allocate extra space for another array, you must do this in place with constant memory.
12 |
13 | For example,
14 | Given input array nums = [1,1,2],
15 |
16 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
17 |
18 | Inspired by @liyangguang1988 at https://leetcode.com/discuss/10314/my-solution-time-o-n-space-o-1
19 |
20 | */
21 |
22 | import Foundation
23 |
24 | class Easy_026_Remove_Duplicates_from_Sorted_Array {
25 | // O (1) space, O(N) time
26 | class func removeDuplicates(_ arr: inout [Int]) -> Int {
27 | if arr.count < 2 {
28 | return arr.count
29 | }
30 | var index: Int = 1
31 | let n: Int = arr.count
32 | for i in 1 ..< n {
33 | if arr[i] != arr[i-1] {
34 | arr[index] = arr[i]
35 | index += 1
36 | }
37 | }
38 | return index
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_027_Remove_Element.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/remove-element/
4 |
5 | #27 Remove Element
6 |
7 | Level: easy
8 |
9 | Given an array and a value, remove all instances of that value in place and return the new length.
10 |
11 | The order of elements can be changed. It doesn't matter what you leave beyond the new length.
12 |
13 | Inspired by @daxianji007 at https://leetcode.com/discuss/3753/my-solution-for-your-reference
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | class Easy_027_Remove_Element {
20 | class func removeElement(arr: inout [Int], elem: Int) -> Int {
21 | var begin: Int = 0
22 | for i in 0 ..< arr.count {
23 | if arr[i] != elem {
24 | arr[begin] = arr[i]
25 | begin += 1
26 | }
27 | }
28 | return begin
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_036_Valid_Sudoku.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/valid-sudoku/
4 |
5 | #36 Valid Sudoku
6 |
7 | Level: easy
8 |
9 | Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
10 |
11 | "Each row must have the numbers 1-9 occuring just once."
12 |
13 | "Each column must have the numbers 1-9 occuring just once."
14 |
15 | "And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid."
16 |
17 | The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
18 |
19 | A partially filled sudoku which is valid.
20 |
21 | Note:
22 | A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
23 |
24 | Inspired by @bigwolfandtiger at https://leetcode.com/discuss/17990/sharing-my-easy-understand-java-solution-using-set
25 |
26 | */
27 |
28 | import Foundation
29 |
30 | class Easy_036_Valid_Sudoku {
31 | class func isPartiallyValid(board: [[Character]], x1: Int, y1: Int, x2: Int, y2: Int) -> Bool {
32 | var singleSet: Set = Set()
33 | for i in x1...x2 {
34 | for j in y1...y2 {
35 | if board[i][j] != "." {
36 | if singleSet.contains(board[i][j]) == true {
37 | return false
38 | } else {
39 | singleSet.insert(board[i][j])
40 | }
41 | }
42 | }
43 | }
44 | return true
45 | }
46 | class func isValidSudoku(_ board: [[Character]]) -> Bool {
47 | for i in 0..<9 {
48 | if isPartiallyValid(board: board, x1: i, y1: 0, x2: i, y2: 8) == false {
49 | return false
50 | }
51 | if isPartiallyValid(board: board, x1: 0, y1: i, x2: 8, y2: i) == false {
52 | return false
53 | }
54 | }
55 | for i in 0..<3 {
56 | for j in 0..<3 {
57 | if isPartiallyValid(board: board, x1: i*3, y1: j*3, x2: i*3+2, y2: j*3+2) == false {
58 | return false
59 | }
60 | }
61 | }
62 | return true
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_038_Count_And_Say.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/count-and-say/
4 |
5 | #38 Count and Say
6 |
7 | Level: easy
8 |
9 | The count-and-say sequence is the sequence of integers beginning as follows:
10 | 1, 11, 21, 1211, 111221, ...
11 |
12 | 1 is read off as "one 1" or 11.
13 | 11 is read off as "two 1s" or 21.
14 | 21 is read off as "one 2, then one 1" or 1211.
15 | Given an integer n, generate the nth sequence.
16 |
17 | Note: The sequence of integers will be represented as a string.
18 |
19 | Inspired by @zerobased at https://leetcode.com/discuss/7678/show-an-answer-in-java
20 |
21 | */
22 |
23 | import Foundation
24 |
25 | private extension String {
26 | subscript (index: Int) -> Character {
27 | return self[self.index(self.startIndex, offsetBy: index)]
28 | }
29 | }
30 |
31 | class Easy_038_Count_And_Say {
32 | class func countAndSay(_ n: Int) -> String {
33 | var result: String = "1"
34 | for _ in 0 ..< n {
35 | let previous: String = result
36 | result = ""
37 | var counter = 1
38 | var say: Character = previous[0]
39 | for j in 1 ..< previous.count {
40 | if previous[j] != say {
41 | result = "\(result)\(counter)\(say)"
42 | counter = 1
43 | say = previous[j]
44 | } else {
45 | counter += 1
46 | }
47 | }
48 | result = "\(result)\(counter)\(say)"
49 | }
50 | return result
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_058_Length_Of_Last_Word.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/length-of-last-word/
4 |
5 | #58 Length of Last Word
6 |
7 | Level: easy
8 |
9 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
10 |
11 | If the last word does not exist, return 0.
12 |
13 | Note: A word is defined as a character sequence consists of non-space characters only.
14 |
15 | For example,
16 | Given s = "Hello World",
17 | return 5.
18 |
19 | Inspired by @eaglesky1990 at https://leetcode.com/discuss/9148/my-simple-solution-in-c
20 |
21 | */
22 |
23 | import Foundation
24 |
25 | private extension String {
26 | subscript (index: Int) -> Character {
27 | return self[self.index(self.startIndex, offsetBy: index)]
28 | }
29 | }
30 |
31 | struct Easy_058_Length_Of_Last_Word {
32 | static func lengthOfLastWord(_ s: String) -> Int {
33 | var len = 0
34 | var i = 0
35 | while i < s.count {
36 | if s[i] != " " {
37 | len += 1
38 | } else if i + 1 < s.count && s[i+1] != " " {
39 | len = 0
40 | }
41 | i += 1
42 | }
43 | return len
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_066_Plus_One.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/plus-one/
4 |
5 | #66 Plus One
6 |
7 | Level: easy
8 |
9 | Given a non-negative number represented as an array of digits, plus one to the number.
10 |
11 | The digits are stored such that the most significant digit is at the head of the list.
12 |
13 | Inspired by @zezedi at https://leetcode.com/discuss/14616/is-it-a-simple-code-c
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | struct Easy_066_Plus_One {
20 | static func plusOne(_ digits: inout [Int]) {
21 | let n = digits.count
22 | for i in (0 ... n-1).reversed() {
23 | if digits[i] == 9 {
24 | digits[i] = 0
25 | } else {
26 | digits[i] += 1
27 | return
28 | }
29 | }
30 | digits[0] = 1
31 | digits.append(0)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_067_Add_Binary.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/add-binary/
4 |
5 | #67 Add Binary
6 |
7 | Given two binary strings, return their sum (also a binary string).
8 |
9 | For example,
10 | a = "11"
11 | b = "1"
12 | Return "100".
13 |
14 | Inspired by @makuiyu at https://leetcode.com/discuss/25593/short-code-by-c
15 |
16 | */
17 |
18 | import Foundation
19 |
20 | private extension String {
21 | subscript (index: Int) -> Character {
22 | return self[self.index(self.startIndex, offsetBy: index)]
23 | }
24 | }
25 |
26 | struct Easy_067_Add_Binary {
27 | static func addBinary(a: String, b: String) -> String {
28 | var s = ""
29 | var c: Int = 0
30 | var i = a.count - 1
31 | var j = b.count - 1
32 | let characterDict: [Character: Int] = [
33 | "0": 0,
34 | "1": 1,
35 | "2": 2,
36 | "3": 3,
37 | "4": 4,
38 | "5": 5,
39 | "6": 6,
40 | "7": 7,
41 | "8": 8,
42 | "9": 9,
43 | ]
44 | let intDict: [Int: String] = [
45 | 0: "0",
46 | 1: "1",
47 | 2: "2",
48 | 3: "3",
49 | 4: "4",
50 | 5: "5",
51 | 6: "6",
52 | 7: "7",
53 | 8: "8",
54 | 9: "9",
55 | ]
56 | while i >= 0 || j >= 0 || c == 1 {
57 | c += i >= 0 ? characterDict[a[i]]! : 0
58 | i -= 1
59 | c += j >= 0 ? characterDict[b[j]]! : 0
60 | j -= 1
61 | s = intDict[c%2]! + s
62 | c /= 2
63 | }
64 | return s
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_070_Climbing_Stairs.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/climbing-stairs/
4 |
5 | #70 Climbing Stairs
6 |
7 | Level: easy
8 |
9 | You are climbing a stair case. It takes n steps to reach to the top.
10 |
11 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
12 |
13 | Inspired by @facetothefate at https://leetcode.com/discuss/2809/easy-solutions-for-suggestions
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | struct Easy_070_Climbing_Stairs {
20 | static func climbStairs(_ n: Int) -> Int {
21 | if n == 0 || n == 1 {
22 | return 1
23 | }
24 | var stepOne = 1
25 | var stepTwo = 1
26 | var result = 0
27 | for _ in 2...n {
28 | result = stepOne + stepTwo
29 | stepTwo = stepOne
30 | stepOne = result
31 | }
32 | return result
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_083_Remove_Duplicates_From_Sorted_List.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list/
4 |
5 | #83 Remove Duplicates from Sorted List
6 |
7 | Level: easy
8 |
9 | Given a sorted linked list, delete all duplicates such that each element appear only once.
10 |
11 | For example,
12 | Given 1->1->2, return 1->2.
13 | Given 1->1->2->3->3, return 1->2->3.
14 |
15 | Inspired by @Tao2014 at https://leetcode.com/discuss/7188/concise-solution-and-memory-freeing
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | class Easy_083_Remove_Duplicates_From_Sorted_List {
22 | class Node {
23 | var value: Int
24 | var next: Node?
25 | init(value: Int, next: Node?) {
26 | self.value = value
27 | self.next = next
28 | }
29 | }
30 | class func deleteDuplicates(_ head: Node?) -> Node? {
31 | if head == nil {
32 | return nil
33 | }
34 | var curr: Node? = head
35 | while curr?.next != nil {
36 | if curr?.value == curr?.next?.value {
37 | curr?.next = curr?.next?.next
38 | } else {
39 | curr = curr?.next
40 | }
41 | }
42 | return head;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_088_Merge_Sorted_Array.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/merge-sorted-array/
4 |
5 | #88 Merge Sorted Array
6 |
7 | Level: easy
8 |
9 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
10 |
11 | Note:
12 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
13 |
14 | Inspired by @leetchunhui at https://leetcode.com/discuss/8233/this-is-my-ac-code-may-help-you
15 |
16 | */
17 |
18 | import Foundation
19 |
20 | struct Easy_088_Merge_Sorted_Array {
21 | static func merge(nums1: inout [Int], m: Int, nums2: [Int], n: Int) {
22 | var i = m - 1
23 | var j = n - 1
24 | var k = m + n - 1
25 | while i >= 0 && j >= 0 {
26 | if nums1[i] > nums2[j] {
27 | nums1[k] = nums1[i]
28 | k -= 1
29 | i -= 1
30 | } else {
31 | nums1[k] = nums2[j]
32 | k -= 1
33 | j -= 1
34 | }
35 | }
36 | while j >= 0 {
37 | nums1[k] = nums2[j]
38 | k -= 1
39 | j -= 1
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_101_Symmetric_Tree.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/symmetric-tree/
4 |
5 | #101 Symmetric Tree
6 |
7 | Level: easy
8 |
9 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
10 |
11 | For example, this binary tree is symmetric:
12 |
13 | 1
14 | / \
15 | 2 2
16 | / \ / \
17 | 3 4 4 3
18 |
19 | But the following is not:
20 |
21 | 1
22 | / \
23 | 2 2
24 | \ \
25 | 3 3
26 |
27 | Inspired by [@xuanaux](https://leetcode.com/discuss/456/recusive-solution-symmetric-optimal-solution-inordertraversal)
28 |
29 | */
30 |
31 | import Foundation
32 |
33 | class Easy_101_Symmetric_Tree {
34 | class Node {
35 | var left: Node?
36 | var right: Node?
37 | var value: Int
38 | init(value: Int, left: Node?, right: Node?) {
39 | self.value = value
40 | self.left = left
41 | self.right = right
42 | }
43 | }
44 | // t = O(N), best s = O(logN), worst s = O(N)
45 | class func isSymmetric(_ root: Node?) -> Bool {
46 | if root == nil {
47 | return true
48 | }
49 | var stack_1: [Node?] = []
50 | var stack_2: [Node?] = []
51 | stack_1.append(root)
52 | stack_2.append(root)
53 | while stack_1.isEmpty == false && stack_2.isEmpty == false {
54 | let tmp_1: Node? = stack_1.popLast()!
55 | let tmp_2: Node? = stack_2.popLast()!
56 | if tmp_1 == nil && tmp_2 == nil {
57 | continue
58 | }
59 | if tmp_1 == nil || tmp_2 == nil {
60 | return false
61 | }
62 | if tmp_1!.value != tmp_2!.value {
63 | return false
64 | }
65 | stack_1.append(tmp_1!.right)
66 | stack_2.append(tmp_2!.left)
67 | stack_1.append(tmp_1!.left)
68 | stack_2.append(tmp_2!.right)
69 | }
70 | return true
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Easy/Easy_102_Binary_Tree_Level_Order_Traversal.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/binary-tree-level-order-traversal/
4 |
5 | #102 Binary Tree Level Order Traversal
6 |
7 | Level: easy
8 |
9 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
10 |
11 | For example: Given binary tree [3,9,20,null,null,15,7],
12 | 3
13 | / \
14 | 9 20
15 | / \
16 | 15 7
17 | return its level order traversal as:
18 | [
19 | [3],
20 | [9,20],
21 | [15,7]
22 | ]
23 |
24 | Inspired by [@d40a](https://discuss.leetcode.com/topic/2399/it-is-my-ac-solution)
25 |
26 | */
27 |
28 | import Foundation
29 |
30 | class Easy_102_Binary_Tree_Level_Order_Traversal {
31 | class Node {
32 | var left: Node?
33 | var right: Node?
34 | var value: Int
35 | init(value v: Int, left l: Node?, right r: Node?) {
36 | self.value = v
37 | self.left = l
38 | self.right = r
39 | }
40 | }
41 | // t = O(N), best s = O(logN), worst s = O(N)
42 | class func levelOrder(_ root: Node?) -> [[Int]] {
43 | guard let unwrappedRoot = root else {
44 | return []
45 | }
46 | var ret: [[Int]] = []
47 | var queue: [(Node, Int)] = [(unwrappedRoot, 0)]
48 | while let pair: (node: Node, index: Int) = queue.first {
49 | if ret.count <= pair.index {
50 | ret.append([Int]())
51 | }
52 | ret[pair.index].append(pair.node.value)
53 | if let l = pair.node.left {
54 | queue.append((l, pair.index + 1))
55 | }
56 | if let r = pair.node.right {
57 | queue.append((r, pair.index + 1))
58 | }
59 | _ = queue.removeFirst()
60 | }
61 | return ret
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_004_Median_Of_Two_Sorted_Arrays.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/median-of-two-sorted-arrays/
4 |
5 | #4 Median of Two Sorted Arrays
6 |
7 | Level: hard
8 |
9 | There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
10 |
11 | Inspired by @MissMary at https://leetcode.com/discuss/15790/share-my-o-log-min-m-n-solution-with-explanation
12 |
13 | */
14 |
15 | struct Hard_004_Median_Of_Two_Sorted_Arrays {
16 | // t = O(log(min(M, N))), s = O(1)
17 | static func findMedianSortedArrays(a: [Int], b: [Int]) -> Double {
18 | let m = a.count
19 | let n = b.count
20 |
21 | if m > n {
22 | return findMedianSortedArrays(a: b, b: a)
23 | }
24 |
25 | var tmpMin = 0
26 | var tmpMax = m
27 | while tmpMin <= tmpMax {
28 | let i = (tmpMin + tmpMax) / 2
29 | let j = ((m + n + 1) / 2) - i
30 | if j > 0 && i < m && b[j-1] > a[i] {
31 | tmpMin = i + 1
32 | } else if i > 0 && j < n && a[i-1] > b[j] {
33 | tmpMax = i - 1
34 | } else {
35 | var firstNum: Int
36 | if i == 0 {
37 | firstNum = b[j-1]
38 | }
39 | else if j == 0 {
40 | firstNum = a[i-1]
41 | }
42 | else {
43 | firstNum = max(a[i-1], b[j-1])
44 | }
45 |
46 | // if (m + n) is odd
47 | if (m+n) & 1 != 0 {
48 | return Double(firstNum)
49 | }
50 |
51 | var secondNum: Int
52 | if i == m {
53 | secondNum = b[j]
54 | } else if j == n {
55 | secondNum = a[i]
56 | } else {
57 | secondNum = min(a[i], b[j])
58 | }
59 |
60 | return Double((firstNum + secondNum))/2.0
61 | }
62 | }
63 | return 0.0
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_032_Longest_Valid_Parentheses.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/longest-valid-parentheses/
4 |
5 | #32 Longest Valid Parentheses
6 |
7 | Level: hard
8 |
9 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
10 |
11 | For "(()", the longest valid parentheses substring is "()", which has length = 2.
12 |
13 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
14 |
15 | Inspired by @jerryrcwong at https://leetcode.com/discuss/8092/my-dp-o-n-solution-without-using-stack
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | private extension String {
22 | subscript (index: Int) -> Character {
23 | return self[self.index(self.startIndex, offsetBy: index)]
24 | }
25 | }
26 |
27 | class Hard_032_Longest_Valid_Parentheses {
28 | class func longestValidParentheses(_ s: String?) -> Int {
29 | if s == nil {
30 | return 0
31 | }
32 | if (s!).count <= 1 {
33 | return 0
34 | }
35 | var currentMax: Int = 0
36 | var longest: [Int] = Array(repeating: 0, count: (s!).count)
37 | for i in 1 ..< (s!).count {
38 | let tmp: Int = i - longest[i-1] - 1
39 | if s![i] == ")" && tmp >= 0 && s![tmp] == "(" {
40 | longest[i] = longest[i-1] + 2 + ((tmp - 1 >= 0) ? longest[tmp-1] : 0)
41 | currentMax = max(longest[i], currentMax)
42 | }
43 | }
44 | return currentMax
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_033_Search_In_Rotated_Sorted_Array.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/search-in-rotated-sorted-array/
4 |
5 | #33 Search in Rotated Sorted Array
6 |
7 | Level: hard
8 |
9 | Suppose a sorted array is rotated at some pivot unknown to you beforehand.
10 |
11 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
12 |
13 | You are given a target value to search. If found in the array return its index, otherwise return -1.
14 |
15 | You may assume no duplicate exists in the array.
16 |
17 | Inspired by @sean hyuntaek at https://leetcode.com/discuss/5707/algorithm-using-binary-search-accepted-some-suggestions-else
18 |
19 | */
20 |
21 | import Foundation
22 |
23 | class Hard_033_Search_In_Rotated_Sorted_Array {
24 | class func search(nums: [Int], target: Int) -> Int {
25 | var start: Int = 0
26 | var end: Int = nums.count - 1
27 | while start <= end {
28 | let mid: Int = (start + end) / 2
29 | if nums[mid] == target {
30 | return mid
31 | }
32 | if nums[start] <= nums[mid] {
33 | if nums[start] <= target && target <= nums[mid] {
34 | end = mid - 1
35 | } else {
36 | start = mid + 1
37 | }
38 | } else {
39 | if nums[mid] <= target && target <= nums[end] {
40 | start = mid + 1
41 | } else {
42 | end = mid - 1
43 | }
44 | }
45 | }
46 | return -1
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_037_Sudoku_Solver.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/sudoku-solver/
4 |
5 | #37 Sudoku Solver
6 |
7 | Level: hard
8 |
9 | Write a program to solve a Sudoku puzzle by filling the empty cells.
10 |
11 | Empty cells are indicated by the character '.'.
12 |
13 | You may assume that there will be only one unique solution.
14 |
15 | Inspired by @power721 at https://leetcode.com/discuss/5958/afraid-cant-solve-problem-interview-because-someone-simplify
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | class Hard_037_Sudoku_Solver {
22 | class func validate(board: inout [[Character]], x: Int, y: Int) -> Bool {
23 | let c: Character = board[x][y]
24 | for i in 0 ..< 9 {
25 | if y != i && board[x][i] == c {
26 | return false
27 | }
28 | if x != i && board[i][y] == c {
29 | return false
30 | }
31 | }
32 | let xx: Int = x / 3 * 3
33 | let yy: Int = y / 3 * 3
34 | for i in xx ..< xx + 3 {
35 | for j in yy ..< yy + 3 {
36 | if x != i && y != j && board[i][j] == c {
37 | return false
38 | }
39 | }
40 | }
41 | return true
42 | }
43 | class func dfs(board: inout [[Character]], position: Int) -> Bool {
44 | let n = board.count
45 | if position == n * n {
46 | return true
47 | }
48 | let x: Int = position / n
49 | let y: Int = position % n
50 | if board[x][y] == "." {
51 | let arr: [Character] = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
52 | for c in arr {
53 | board[x][y] = c
54 | if validate(board: &board, x: x, y: y) && dfs(board: &board, position: position + 1) {
55 | return true
56 | }
57 | board[x][y] = "."
58 | }
59 | } else {
60 | if dfs(board: &board, position: position + 1) == true {
61 | return true
62 | }
63 | }
64 | return false
65 | }
66 | class func solveSudoku(_ board: inout [[Character]]) {
67 | let _ = dfs(board: &board, position: 0)
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_041_First_Missing_Positive.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/first-missing-positive/
4 |
5 | #41 First Missing Positive
6 |
7 | Level: hard
8 |
9 | Given an unsorted integer array, find the first missing positive integer.
10 |
11 | For example,
12 | Given [1,2,0] return 3,
13 | and [3,4,-1,1] return 2.
14 |
15 | Your algorithm should run in O(n) time and uses constant space.
16 |
17 | Inspired by @makuiyu at https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time
18 |
19 | */
20 |
21 | import Foundation
22 |
23 | struct Hard_041_First_Missing_Positive {
24 | static func firstMissingPositive(_ n: [Int]) -> Int {
25 | var nums = n
26 | for i in 0 ..< nums.count {
27 | while nums[i] > 0 && nums[i] <= nums.count && nums[nums[i]-1] != nums[i] {
28 | nums.swapAt(i, nums[i]-1)
29 | }
30 | }
31 | for i in 0 ..< nums.count {
32 | if(nums[i] != i+1) {
33 | return i + 1;
34 | }
35 | }
36 | return nums.count + 1;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_042_Trapping_Rain_Water.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/trapping-rain-water/
4 |
5 | #Level: hard
6 |
7 | #42 Trapping Rain Water
8 |
9 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
10 |
11 | For example,
12 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
13 |
14 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
15 |
16 | Inspired by @12344 at https://leetcode.com/discuss/3546/any-one-pass-solutions
17 |
18 | */
19 |
20 | import Foundation
21 |
22 | struct Hard_042_Trapping_Rain_Water {
23 | static func trap(_ nums: [Int]) -> Int {
24 | if nums.count == 0 {
25 | return 0
26 | }
27 | var left = 0
28 | var right = nums.count - 1
29 | var block = 0
30 | var all = 0
31 | var currLevel = 0
32 | while left <= right {
33 | if min(nums[left], nums[right]) > currLevel {
34 | all += (min(nums[left], nums[right]) - currLevel) * (right - left + 1)
35 | currLevel = min(nums[left], nums[right])
36 | }
37 | if nums[left] < nums[right] {
38 | block += nums[left]
39 | left += 1
40 | } else {
41 | block += nums[right]
42 | right -= 1
43 | }
44 | }
45 | return all - block
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_044_Wildcard_Matching.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/wildcard-matching/
4 |
5 | #44 Wildcard Matching
6 |
7 | Level: hard
8 |
9 | Implement wildcard pattern matching with support for '?' and '*'.
10 |
11 | '?' Matches any single character.
12 | '*' Matches any sequence of characters (including the empty sequence).
13 |
14 | The matching should cover the entire input string (not partial).
15 |
16 | The function prototype should be:
17 | bool isMatch(const char *s, const char *p)
18 |
19 | Some examples:
20 | isMatch("aa","a") → false
21 | isMatch("aa","aa") → true
22 | isMatch("aaa","aa") → false
23 | isMatch("aa", "*") → true
24 | isMatch("aa", "a*") → true
25 | isMatch("ab", "?*") → true
26 | isMatch("aab", "c*a*b") → false
27 |
28 | Inspired by @pandora111 at https://leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution
29 |
30 | */
31 |
32 | import Foundation
33 |
34 | private extension String {
35 | subscript(index: Int) -> Character {
36 | return self[self.index(self.startIndex, offsetBy: index)]
37 | }
38 | }
39 |
40 | struct Hard_044_Wildcard_Matching {
41 | static func isMatch(s: String, p: String) -> Bool {
42 | var sIndex = 0
43 | var pIndex = 0
44 | var match = 0
45 | var startIndex = -1
46 | while sIndex < s.count {
47 | if pIndex < p.count && (p[pIndex] == "?" || s[sIndex] == p[pIndex]) {
48 | sIndex += 1
49 | pIndex += 1
50 | } else if pIndex < p.count && p[pIndex] == "*" {
51 | startIndex = pIndex
52 | match = sIndex
53 | pIndex += 1
54 | } else if startIndex != -1 {
55 | pIndex = startIndex + 1
56 | match += 1
57 | sIndex = match
58 | } else {
59 | return false
60 | }
61 | }
62 | while pIndex < p.count && p[pIndex] == "*" {
63 | pIndex += 1
64 | }
65 | return pIndex == p.count
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_045_Jump_Game_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/jump-game-ii/
4 |
5 | #45 Jump Game II
6 |
7 | Level: hard
8 |
9 | Given an array of non-negative integers, you are initially positioned at the first index of the array.
10 |
11 | Each element in the array represents your maximum jump length at that position.
12 |
13 | Your goal is to reach the last index in the minimum number of jumps.
14 |
15 | For example:
16 | Given array A = [2,3,1,1,4]
17 |
18 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
19 |
20 | Inspired by @chentao169 at https://leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii
21 |
22 | */
23 |
24 | import Foundation
25 |
26 | struct Hard_045_Jump_Game_II {
27 | static func jump(_ nums: [Int]) -> Int {
28 | var result = 0;
29 | var last = 0;
30 | var curr = 0;
31 | for i in 0 ..< nums.count{
32 | if (i > last) {
33 | last = curr;
34 | result += 1;
35 | }
36 | curr = max(curr, i+nums[i]);
37 | }
38 | return result;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_047_Permutations_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/permutations-ii/
4 |
5 | #47 Permutations II
6 |
7 | Level: hard
8 |
9 | Given a collection of numbers that might contain duplicates, return all possible unique permutations.
10 |
11 | For example,
12 | [1,1,2] have the following unique permutations:
13 | [1,1,2], [1,2,1], and [2,1,1].
14 |
15 | Inspired by @TransMatrix at https://leetcode.com/discuss/10609/a-non-recursive-c-implementation-with-o-1-space-cost
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | struct Hard_047_Permutations_II {
22 | private static func reverseInPlace(nums: inout [Int], begin bgn: Int, end ed: Int) {
23 | var begin = bgn
24 | var end = ed
25 | while begin < end {
26 | nums.swapAt(begin, end);
27 | begin += 1
28 | end -= 1
29 | }
30 | }
31 | static func permuteUnique(_ n: [Int]) -> [[Int]] {
32 | var nums = n
33 | var result = [[Int]]()
34 | nums.sort {$0 < $1}
35 | result.append(nums)
36 | while true {
37 | var i: Int = nums.count - 1
38 | for _ in (1 ..< nums.count).reversed() {
39 | if nums[i-1] < nums[i] {
40 | break
41 | }
42 | i -= 1
43 | }
44 | if i == 0 {
45 | break
46 | }
47 | var j: Int = nums.count - 1
48 | for _ in (i ..< nums.count).reversed() {
49 | if nums[j] > nums[i-1] {
50 | break
51 | }
52 | j -= 1
53 | }
54 | nums.swapAt(i-1, j)
55 | reverseInPlace(nums: &nums, begin: i, end: nums.count-1)
56 | result.append(nums)
57 | }
58 | return result
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_051_N_Queens.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/n-queens/
4 |
5 | #51 N-Queens
6 |
7 | Level: hard
8 |
9 | The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
10 |
11 | Given an integer n, return all distinct solutions to the n-queens puzzle.
12 |
13 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
14 |
15 | For example,
16 | There exist two distinct solutions to the 4-queens puzzle:
17 |
18 | [
19 | [".Q..", // Solution 1
20 | "...Q",
21 | "Q...",
22 | "..Q."],
23 |
24 | ["..Q.", // Solution 2
25 | "Q...",
26 | "...Q",
27 | ".Q.."]
28 | ]
29 |
30 | Inspired by @qqz003 at https://leetcode.com/discuss/22526/c-6ms-solution-use-bitmask
31 |
32 | */
33 |
34 | import Foundation
35 |
36 | struct Hard_051_N_Queens {
37 | private static func getNq(index: Int, n: Int) -> String {
38 | var charArr = [Character](repeating: ".", count: n)
39 | charArr[index] = "Q"
40 | return String(charArr)
41 | }
42 | private static func nQueens(n: Int, p: Int, l: Int, m: Int, r: Int, answer: inout [String], result: inout [[String]]) {
43 | if p >= n {
44 | result.append(answer)
45 | return
46 | }
47 | let mask = l | m | r
48 | var i = 0
49 | var b = 1
50 | while i < n {
51 | if mask & b == 0 {
52 | answer.append(getNq(index: i, n: n))
53 | nQueens(n: n, p: p+1, l: (l | b) >> 1, m: m | b, r: (r | b) << 1, answer: &answer, result: &result)
54 | answer.removeLast()
55 | }
56 | i += 1
57 | b <<= 1
58 | }
59 | }
60 | static func solveNQueens(_ n: Int) -> [[String]] {
61 | var result = [[String]]()
62 | var answer = [String]()
63 | nQueens(n: n, p: 0, l: 0, m: 0, r: 0, answer: &answer, result: &result)
64 | return result
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_052_N_Queens_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/n-queens-ii/
4 |
5 | #52 N-Queens II
6 |
7 | Follow up for N-Queens problem.
8 |
9 | Now, instead outputting board configurations, return the total number of distinct solutions.
10 |
11 | Inspired by @qiqjiao at https://leetcode.com/discuss/743/whats-your-solution
12 |
13 | */
14 |
15 | import Foundation
16 |
17 | struct Hard_052_N_Queens_II {
18 | private static func dfs(h: Int, r: Int, l: Int, answer: inout Int, limit: inout Int) {
19 | if h == limit {
20 | answer += 1
21 | return
22 | }
23 | var position = limit & (~(h|r|l))
24 | while position > 0 {
25 | let p = position & (-position)
26 | position -= p
27 | dfs(h: h+p, r: (r+p)<<1, l: (l+p)>>1, answer: &answer, limit: &limit)
28 | }
29 | }
30 | static func totalNQueens(_ n: Int) -> Int {
31 | if n == 0 {
32 | return 0
33 | }
34 | var answer = 0
35 | var limit = (1< [[Int]] {
23 | var intervals = itv
24 | if intervals.count <= 1 {
25 | return intervals
26 | }
27 | intervals.sort { (elm1, elm2) -> Bool in
28 | let e1 = elm1
29 | let e2 = elm2
30 | return e1[0] <= e2[0]
31 | }
32 | var res = [[Int]]()
33 | var start = intervals[0][0]
34 | var end = intervals[0][1]
35 |
36 | for i in intervals {
37 | if i[0] <= end {
38 | end = max(end, i[1])
39 | } else {
40 | res.append([start, end])
41 | start = i[0]
42 | end = i[1]
43 | }
44 | }
45 |
46 | res.append([start, end])
47 | return res
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_057_Insert_Interval.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/discuss/3971/in-place-solution-ask-for-suggestion
4 |
5 | #57 Insert Interval
6 |
7 | Level: hard
8 |
9 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
10 |
11 | You may assume that the intervals were initially sorted according to their start times.
12 |
13 | Example 1:
14 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
15 |
16 | Example 2:
17 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
18 |
19 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
20 |
21 | Inspired by @stellari at https://leetcode.com/discuss/3971/in-place-solution-ask-for-suggestion
22 |
23 | */
24 |
25 | import Foundation
26 |
27 | struct Hard_057_Insert_Interval {
28 | static func insert(intervals: [[Int]], newInterval newI: [Int]) -> [[Int]] {
29 | var newInterval = newI
30 | var res: [[Int]] = []
31 | for i in 0 ..< intervals.count {
32 | if newInterval[0] > intervals[i][1] {
33 | res.append(intervals[i])
34 | } else if newInterval[1] < intervals[i][0] {
35 | res.append(newInterval)
36 | newInterval = intervals[i]
37 | } else {
38 | newInterval[0] = min(newInterval[0], intervals[i][0])
39 | newInterval[1] = max(newInterval[1], intervals[i][1])
40 | }
41 | }
42 | res.append(newInterval)
43 | return res
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_072_Edit_Distance.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/edit-distance/
4 |
5 | #72 Edit Distance
6 |
7 | Level: hard
8 |
9 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
10 |
11 | You have the following 3 operations permitted on a word:
12 |
13 | a) Insert a character
14 | b) Delete a character
15 | c) Replace a character
16 |
17 | Inspired by @eaglesky1990 at https://leetcode.com/discuss/10426/my-o-mn-time-and-o-n-space-solution-using-dp-with-explanation
18 |
19 | */
20 |
21 | import Foundation
22 |
23 | private extension String {
24 | subscript (index: Int) -> Character {
25 | return self[self.index(self.startIndex, offsetBy: index)]
26 | }
27 | }
28 |
29 | struct Hard_072_Edit_Distance {
30 | static func minDistance(word1 w1: String, word2 w2: String) -> Int {
31 | var word1 = w1
32 | var word2 = w2
33 | var len1 = word1.count
34 | var len2 = word2.count
35 | if len1 < len2 {
36 | swap(&word1, &word2)
37 | swap(&len1, &len2)
38 | }
39 | var buf: [Int] = Array(repeating: 0, count: len2 + 1)
40 | if len2 > 0 {
41 | for j in 1...len2{
42 | buf[j] = j
43 | }
44 | }
45 | if len1 > 0 {
46 | for i in 1...len1{
47 | var prev = i
48 | if len2 > 0 {
49 | for j in 1...len2 {
50 | var curr: Int
51 | if word1[i-1] == word2[j-1] {
52 | curr = buf[j-1]
53 | } else {
54 | curr = min(buf[j-1], prev, buf[j]) + 1
55 | }
56 | buf[j-1] = prev
57 | prev = curr
58 | }
59 | }
60 | buf[len2] = prev
61 | }
62 | }
63 | return buf[len2]
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_084_Largest_Rectangle_In_Histogram.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/largest-rectangle-in-histogram/
4 |
5 | #84 Largest Rectangle in Histogram
6 |
7 | Level: hard
8 |
9 | Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
10 |
11 |
12 | Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
13 |
14 |
15 | The largest rectangle is shown in the shaded area, which has area = 10 unit.
16 |
17 | For example,
18 | Given height = [2,1,5,6,2,3],
19 | return 10.
20 |
21 | Inspired by http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
22 |
23 | */
24 |
25 | import Foundation
26 |
27 | struct Hard_084_Largest_Rectangle_In_Histogram {
28 | static func largestRectangleArea(_ heights: [Int]) -> Int {
29 | var stack:[Int] = []
30 | var max_area = 0
31 | var top_of_stack: Int
32 | var area_with_top: Int
33 | var i = 0
34 | while i < heights.count {
35 | if stack.isEmpty || heights[stack.last!] <= heights[i] {
36 | stack.append(i)
37 | i += 1
38 | } else {
39 | top_of_stack = stack.last!
40 | stack.removeLast()
41 | area_with_top = heights[top_of_stack] * (stack.isEmpty ? i : i - stack.last! - 1)
42 | if max_area < area_with_top {
43 | max_area = area_with_top
44 | }
45 | }
46 | }
47 | while stack.isEmpty == false {
48 | top_of_stack = stack.last!
49 | stack.removeLast()
50 | area_with_top = heights[top_of_stack] * (stack.isEmpty ? i : i - stack.last! - 1)
51 | if max_area < area_with_top {
52 | max_area = area_with_top
53 | }
54 | }
55 | return max_area
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_085_Maximal_Rectangle.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/maximal-rectangle/
4 |
5 | #85 Maximal Rectangle
6 |
7 | Level: hard
8 |
9 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
10 |
11 | Inspired by @morrischen2008 at https://leetcode.com/discuss/20240/share-my-dp-solution
12 |
13 | */
14 |
15 | import Foundation
16 |
17 | struct Hard_085_Maximal_Rectangle {
18 | static func maximalRectangle(_ matrix: [[Character]]) -> Int {
19 | if matrix.isEmpty {
20 | return 0
21 | }
22 | let m: Int = matrix.count
23 | let n: Int = matrix[0].count
24 | var left: [Int] = [Int](repeating: 0, count: n)
25 | var right: [Int] = [Int](repeating: n, count: n)
26 | var height: [Int] = [Int](repeating: 0, count: n)
27 | var maxArea: Int = 0
28 | for i in 0 ..< m {
29 | var curr_left = 0
30 | var curr_right = n
31 | for j in 0 ..< n {
32 | if matrix[i][j] == "1" {
33 | height[j] = height[j] + 1
34 | } else {
35 | height[j] = 0
36 | }
37 | }
38 | for j in 0 ..< n {
39 | if matrix[i][j] == "1" {
40 | left[j] = max(left[j], curr_left)
41 | } else {
42 | left[j] = 0
43 | curr_left = j + 1
44 | }
45 | }
46 | if n >= 1 {
47 | for j in (0...n-1).reversed() {
48 | if matrix[i][j] == "1" {
49 | right[j] = min(right[j], curr_right)
50 | } else {
51 | right[j] = n
52 | curr_right = j
53 | }
54 | }
55 | }
56 | for j in 0 ..< n {
57 | maxArea = max(maxArea, (right[j] - left[j]) * height[j])
58 | }
59 | }
60 | return maxArea
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Hard/Hard_097_Interleaving_String.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/interleaving-string/
4 |
5 | #97 Interleaving String
6 |
7 | Level: hard
8 |
9 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
10 |
11 | For example,
12 | Given:
13 | s1 = "aabcc",
14 | s2 = "dbbca",
15 |
16 | When s3 = "aadbbcbcac", return true.
17 | When s3 = "aadbbbaccc", return false.
18 |
19 | Inspired by @sherryxmhe at https://leetcode.com/discuss/11694/my-dp-solution-in-c
20 |
21 | */
22 |
23 | import Foundation
24 |
25 | private extension String {
26 | subscript(index: Int) -> Character {
27 | return self[self.index(self.startIndex, offsetBy: index)]
28 | }
29 | }
30 |
31 | struct Hard_097_Interleaving_String {
32 | // t = O(N*M), s = O(N*M)
33 | static func isInterleave(s1: String, s2: String, s3: String) -> Bool {
34 | if s1.count + s2.count != s3.count {
35 | return false
36 | }
37 | var dp: [[Bool]] = Array>(repeating: Array(repeating: false, count: s2.count+1), count: s1.count+1)
38 | for i in 0 ..< s1.count + 1{
39 | for j in 0 ..< s2.count + 1{
40 | if i == 0 && j == 0 {
41 | dp[0][0] = true
42 | } else if i == 0 {
43 | dp[0][j] = dp[0][j-1] && (s2[j-1] == s3[j-1])
44 | } else if j == 0 {
45 | dp[i][0] = dp[i-1][0] && (s1[i-1] == s3[i-1])
46 | } else {
47 | dp[i][j] = (dp[i][j-1] && (s2[j-1] == s3[i+j-1])) || (dp[i-1][j] && (s1[i-1] == s3[i+j-1]))
48 | }
49 | }
50 | }
51 | return dp[s1.count][s2.count]
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/Solutions/Solutions/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIMainStoryboardFile
28 | Main
29 | UIRequiredDeviceCapabilities
30 |
31 | armv7
32 |
33 | UISupportedInterfaceOrientations
34 |
35 | UIInterfaceOrientationPortrait
36 | UIInterfaceOrientationLandscapeLeft
37 | UIInterfaceOrientationLandscapeRight
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_001_Two_Sum.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://oj.leetcode.com/problems/two-sum/
4 |
5 | #1 Two Sum
6 |
7 | Level: medium
8 |
9 | Given an array of integers, find two numbers such that they add up to a specific target number.
10 |
11 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
12 |
13 | You may assume that each input would have exactly one solution.
14 |
15 | Input: numbers={2, 7, 11, 15}, target=9
16 | Output: index1=1, index2=2
17 |
18 | Inspired by @naveed.zafar at https://leetcode.com/discuss/10947/accepted-c-o-n-solution
19 |
20 | */
21 |
22 | struct Medium_001_Two_Sum {
23 | // t = O(N), s = O(N)
24 | static func twoSum(numbers: [Int], target: Int) -> [Int] {
25 | var hashMap = [Int: Int]()
26 | var result = [Int]()
27 |
28 | for i in 0.. 4 -> 3) + (5 -> 6 -> 4)
12 | Output: 7 -> 0 -> 8
13 |
14 | Inspired by @potpie at https://oj.leetcode.com/discuss/2308/is-this-algorithm-optimal-or-what
15 |
16 | */
17 |
18 | class Medium_002_Add_Two_Numbers {
19 | // Linked List Data Structure
20 | class ListNode {
21 | var value: Int
22 | var next: ListNode?
23 | init () {
24 | value = 0
25 | next = nil
26 | }
27 | init (nodeValue: Int, nodeNext: ListNode?) {
28 | value = nodeValue
29 | next = nodeNext
30 | }
31 | }
32 |
33 | // t = O(N), s = O(1)
34 | static func addNumbers(_ node1: ListNode?, node2: ListNode?) -> ListNode? {
35 | var tmp1: ListNode? = node1
36 | var tmp2: ListNode? = node2
37 | let dummy: ListNode = ListNode()
38 | var curr: ListNode = dummy
39 | var sum: Int = 0
40 |
41 | while tmp1 != nil || tmp2 != nil {
42 | sum /= 10
43 | if let n = tmp1 {
44 | sum += n.value
45 | tmp1 = n.next
46 | }
47 | if let n = tmp2 {
48 | sum += n.value
49 | tmp2 = n.next
50 | }
51 | curr.next = ListNode(nodeValue: sum%10, nodeNext: nil)
52 | if let n = curr.next {
53 | curr = n
54 | }
55 | }
56 |
57 | if sum / 10 == 1 {
58 | curr.next = ListNode(nodeValue: 1, nodeNext: nil)
59 | }
60 |
61 | return dummy.next
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_011_Container_With_Most_Water.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/container-with-most-water/
4 |
5 | #11 Container With Most Water
6 |
7 | Level: medium
8 |
9 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
10 |
11 | Note: You may not slant the container.
12 |
13 | Inspired by @franticguy at https://leetcode.com/discuss/14610/very-simple-o-n-solution
14 |
15 | */
16 |
17 | class Medium_011_Container_With_Most_Water {
18 | // O (N)
19 | class func maxArea(heightsArray: [Int]) -> Int {
20 | var j: Int = heightsArray.count - 1
21 | var i: Int = 0
22 | var mx: Int = 0
23 |
24 | while i < j {
25 | mx = max(mx, (j-i) * min(heightsArray[i], heightsArray[j]))
26 |
27 | if heightsArray[i] < heightsArray[j] {
28 | i += 1
29 | } else {
30 | j -= 1
31 | }
32 | }
33 | return mx
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_012_Integer_To_Roman.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/integer-to-roman/
4 |
5 | #12 Integer To Roman
6 |
7 | Level: medium
8 |
9 | Given an integer, convert it to a roman numeral.
10 |
11 | Input is guaranteed to be within the range from 1 to 3999.
12 |
13 | Inspired by @flytosky at https://leetcode.com/discuss/1208/how-to-improve-code
14 |
15 | */
16 |
17 | class Medium_012_Integer_To_Roman {
18 |
19 | // 0, 1000, 2000, 3000
20 | private static var M: [String] = ["", "M", "MM", "MMM"]
21 |
22 | // 0, 100, 200, 300, 400, 500, 600, 700, 800, 900
23 | private static var C: [String] = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
24 |
25 | // 0, 10, 20, 30, 40, 50, 60, 70, 80, 90,
26 | private static var X: [String] = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
27 |
28 | // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
29 | private static var I: [String] = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
30 |
31 | // O (1)
32 | class func integerToRoman(num: Int) -> String {
33 | let m = M[num/1000]
34 | let c = C[(num%1000)/100]
35 | let x = X[(num%100)/10]
36 | let i = I[num%10]
37 | return m + c + x + i
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_015_3Sum.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/3sum/
4 |
5 | #15 3Sum
6 |
7 | Level: medium
8 |
9 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
10 |
11 | Note:
12 | Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
13 | The solution set must not contain duplicate triplets.
14 | For example, given array S = {-1 0 1 2 -1 -4},
15 |
16 | A solution set is:
17 | (-1, 0, 1)
18 | (-1, -1, 2)
19 |
20 | Inspired by @peerlessbloom at https://leetcode.com/discuss/10756/my-accepted-o-n-2-solution-without-hashmap
21 |
22 | */
23 |
24 | struct Medium_015_3Sum {
25 | // O (N^2)
26 | static func threeSum(_ num: [Int]) -> [[Int]] {
27 | var res: [[Int]] = []
28 | if num.count < 3 {
29 | return res
30 | } else {
31 | let sorted: [Int] = num.sorted {$0 < $1}
32 | var twoSum: Int
33 | let size: Int = sorted.count
34 | var i = 0
35 | while i < size - 2 {
36 | var l: Int = i + 1
37 | var r: Int = size - 1
38 | twoSum = 0 - sorted[i]
39 | while l < r {
40 | if sorted[l] + sorted[r] < twoSum {
41 | l += 1
42 | } else if sorted[l] + sorted[r] == twoSum {
43 | var three: [Int] = []
44 | three.append(sorted[i])
45 | three.append(sorted[l])
46 | three.append(sorted[r])
47 | res.append(three)
48 | repeat {
49 | l += 1
50 | } while l < r && sorted[l-1] == sorted[l]
51 | repeat {
52 | r -= 1
53 | } while l < r && sorted[r+1] == sorted[r]
54 | } else {
55 | r -= 1
56 | }
57 | }
58 | repeat {
59 | i += 1
60 | } while i < size - 1 && sorted[i-1] == sorted[i]
61 | }
62 | return res
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_016_3Sum_Closest.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/3sum-closest/
4 |
5 | #16 3Sum Closest
6 |
7 | Level: medium
8 |
9 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
10 |
11 | For example, given array S = {-1 2 1 -4}, and target = 1.
12 |
13 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
14 |
15 | Inspired by @vaibhavatul47 at https://leetcode.com/discuss/6438/a-n-2-solution-can-we-do-better
16 |
17 | */
18 |
19 | struct Medium_016_3Sum_Closest {
20 | // O( N^2 )
21 | static func threeSumClosest(num: [Int], target: Int) -> Int {
22 | let n: Int = num.count
23 | if n <= 3 {
24 | return num.reduce(0, +)
25 | } else {
26 | var ans: Int = 0
27 | var sum: Int
28 | let sorted: [Int] = num.sorted { $0 < $1 }
29 | ans = sorted[0] + sorted[1] + sorted[2]
30 | for i in 0 ..< n-2 {
31 | var j: Int = i+1
32 | var k: Int = n-1
33 | while (j < k) {
34 | sum = sorted[i] + sorted[j] + sorted[k]
35 | if abs(target - ans) > abs(target - sum) {
36 | ans = sum
37 | if ans == target {
38 | return ans
39 | }
40 | }
41 | k -= 1
42 | j += 1
43 | }
44 | }
45 | return ans
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_017_Letter_Combinations_Of_A_Phone_Number.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/letter-combinations-of-a-phone-number/
4 |
5 | #17 Letter Combinations of a Phone Number
6 |
7 | Level: medium
8 |
9 | Given a digit string, return all possible letter combinations that the number could represent.
10 |
11 | A mapping of digit to letters (just like on the telephone buttons) is given below.
12 |
13 | 2 -> abc
14 | 3 -> def
15 | 4 -> ghi
16 | 5 -> jkl
17 | 6 -> mno
18 | 7 -> pqrs
19 | 8 -> tuv
20 | 9 -> wxyz
21 |
22 | Input:Digit string "23"
23 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
24 |
25 | Note:
26 | Although the above answer is in lexicographical order, your answer could be in any order you want.
27 |
28 | Inspired by @lirensun at https://leetcode.com/discuss/24431/my-java-solution-with-fifo-queue
29 |
30 | */
31 |
32 | private extension String {
33 | subscript(index: Int) -> Character {
34 | return self[self.index(self.startIndex, offsetBy: index)]
35 | }
36 | }
37 |
38 | private let mapping: [String] = [
39 | "0",
40 | "1",
41 | "abc",
42 | "def",
43 | "ghi",
44 | "jkl",
45 | "mno",
46 | "pqrs",
47 | "tuv",
48 | "wxyz"
49 | ]
50 |
51 | struct Medium_017_Letter_Combinations_Of_A_Phone_Number {
52 | // t = O(3^N), s = O(3^N)
53 | static func letterCombinations(_ digits: String) -> [String] {
54 | var ans: [String] = []
55 | ans.append("")
56 | for i in 0 ..< digits.count {
57 | let intValue: Int = Int(String(digits[i]))!
58 | while ans.first?.count == i {
59 | let tmp: String = ans.removeFirst()
60 | for c in mapping[intValue] {
61 | ans.append("\(tmp)\(c)")
62 | }
63 | }
64 | }
65 | return ans
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_022_Generate_Parentheses.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/generate-parentheses/
4 |
5 | #22 Generate Parentheses
6 |
7 | Level: medium
8 |
9 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
10 |
11 | For example, given n = 3, a solution set is:
12 |
13 | "((()))", "(()())", "(())()", "()(())", "()()()"
14 |
15 | Inspired by @klyc0k at https://leetcode.com/discuss/14436/concise-recursive-c-solution
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | struct Medium_022_Generate_Parentheses {
22 | static func helper(arr: inout [String], str: String, n: Int, m: Int) {
23 | if m == 0 && n == 0 {
24 | arr.append(str)
25 | return
26 | }
27 | if m > 0 {
28 | helper(arr: &arr, str: str + ")", n: n, m: m-1)
29 | }
30 | if n > 0 {
31 | helper(arr: &arr, str: str + "(", n: n-1, m: m+1)
32 | }
33 | }
34 | static func generateParenthesis(_ n: Int) -> [String] {
35 | var arr: [String] = []
36 | helper(arr: &arr, str: "", n: n, m: 0)
37 | return arr
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_024_Swap_Nodes_In_Pairs.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/swap-nodes-in-pairs/
4 |
5 | #24 Swap Nodes in Pairs
6 |
7 | Level: medium
8 |
9 | Given a linked list, swap every two adjacent nodes and return its head.
10 |
11 | For example,
12 | Given 1->2->3->4, you should return the list as 2->1->4->3.
13 |
14 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
15 |
16 | Inspired by @mike3 at https://leetcode.com/discuss/3608/seeking-for-a-better-solution
17 |
18 | */
19 |
20 | import Foundation
21 |
22 | class Medium_024_Swap_Nodes_In_Pairs {
23 | class Node {
24 | var value: Int
25 | var next: Node?
26 | init(value: Int, next: Node?) {
27 | self.value = value
28 | self.next = next
29 | }
30 | }
31 | class func swap(next1: Node, next2: Node) -> Node {
32 | next1.next = next2.next
33 | next2.next = next1
34 | return next2
35 | }
36 | class func swapPairs(_ head: Node?) -> Node? {
37 | let dummy: Node = Node(value: 0, next: nil)
38 | dummy.next = head
39 | var curr: Node? = dummy
40 | while curr?.next != nil && curr?.next?.next != nil {
41 | curr?.next = swap(next1: curr!.next!, next2: curr!.next!.next!)
42 | curr = curr?.next?.next
43 | }
44 | return dummy.next
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_029_Divide_Two_Integers.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/divide-two-integers/
4 |
5 | #29 Divide Two Integers
6 |
7 | Level: meidum
8 |
9 | Divide two integers without using multiplication, division and mod operator.
10 |
11 | If it is overflow, return MAX_INT.
12 |
13 | Inspired by @lucastan & @ngcl at https://leetcode.com/discuss/11358/simple-o-log-n-2-c-solution
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | struct Medium_029_Divide_Two_Integers {
20 | static func divide(dividend: Int, divisor: Int) -> Int {
21 | if divisor == 0 {
22 | return Int.max
23 | }
24 | if divisor == 1 {
25 | return dividend
26 | }
27 | if dividend == Int.min && divisor == Int.min {
28 | return 1
29 | }
30 | if dividend == Int.min && abs(divisor) == 1 {
31 | return Int.max
32 | }
33 | var answer: UInt = 0
34 | var absDividend: UInt = dividend == Int.min ? UInt(UInt(Int.max) + 1) : UInt(abs(dividend))
35 | let absDivisor: UInt = divisor == Int.min ? UInt(UInt(Int.max) + 1) : UInt(abs(divisor))
36 | while absDividend >= absDivisor {
37 | var tmp: UInt = UInt(absDivisor)
38 | var power: UInt = 1
39 | while tmp << 1 < absDividend {
40 | tmp <<= 1
41 | power <<= 1
42 | }
43 | answer += power
44 | absDividend -= tmp
45 | }
46 | if (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) {
47 | return 0 - Int(answer)
48 | }
49 | return Int(answer)
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_031_Next_Permutation.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/next-permutation/
4 |
5 | #31 Next Permutation
6 |
7 | Level: medium
8 |
9 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
10 |
11 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
12 |
13 | The replacement must be in-place, do not allocate extra memory.
14 |
15 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
16 | 1,2,3 → 1,3,2
17 | 3,2,1 → 1,2,3
18 | 1,1,5 → 1,5,1
19 |
20 | Inspired by @yuyibestman at https://leetcode.com/discuss/8472/share-my-o-n-time-solution
21 |
22 | */
23 |
24 | import Foundation
25 |
26 | struct Medium_031_Next_Permutation {
27 | static func reverseInPlace(nums: inout [Int], start: Int, end: Int) {
28 | if start > end {
29 | return
30 | }
31 | for i in start ... (start + end)/2 {
32 | nums.swapAt(i, start + end - i)
33 | }
34 | }
35 | static func nextPermutation(_ nums: inout [Int]) {
36 | let length: Int = nums.count
37 | if length < 2 {
38 | return
39 | }
40 | var index: Int = length - 1
41 | while index > 0 {
42 | if nums[index - 1] < nums[index] {
43 | break
44 | }
45 | index -= 1
46 | }
47 | if index == 0 {
48 | reverseInPlace(nums: &nums, start: 0, end: length - 1)
49 | } else {
50 | let value: Int = nums[index - 1]
51 | var i: Int = length - 1
52 | while i >= index {
53 | if nums[i] > value {
54 | break
55 | }
56 | i -= 1
57 | }
58 | nums.swapAt(i, index-1)
59 | reverseInPlace(nums: &nums, start: index, end: length - 1)
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_034_Search_For_A_Range.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/search-for-a-range/
4 |
5 | #34 Search for a Range
6 |
7 | Level: medium
8 |
9 | Given a sorted array of integers, find the starting and ending position of a given target value.
10 |
11 | Your algorithm's runtime complexity must be in the order of O(log n).
12 |
13 | If the target is not found in the array, return [-1, -1].
14 |
15 | For example,
16 | Given [5, 7, 7, 8, 8, 10] and target value 8,
17 | return [3, 4].
18 |
19 | Inspired by @stellari at https://leetcode.com/discuss/18242/clean-iterative-solution-binary-searches-with-explanation
20 |
21 | */
22 |
23 | import Foundation
24 |
25 | struct Medium_034_Search_For_A_Range {
26 | static func searchRange(nums: [Int], target: Int) -> [Int] {
27 | var i: Int = 0
28 | var j: Int = nums.count - 1
29 | var result: [Int] = Array(repeating: -1, count: 2)
30 | while i < j {
31 | let mid: Int = (i+j)/2
32 | if nums[mid] < target {
33 | i = mid + 1
34 | } else {
35 | j = mid
36 | }
37 | }
38 | if nums[i] != target {
39 | return result
40 | } else {
41 | result[0] = i
42 | }
43 | j = nums.count - 1
44 | while i < j {
45 | let mid: Int = (i+j)/2 + 1
46 | if nums[mid] > target {
47 | j = mid - 1
48 | } else {
49 | i = mid
50 | }
51 | }
52 | result[1] = j
53 | return result
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_035_Search_Insert_Position.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/search-insert-position/
4 |
5 | #35 Search Insert Position
6 |
7 | Level: medium
8 |
9 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
10 |
11 | You may assume no duplicates in the array.
12 |
13 | Here are few examples.
14 | [1,3,5,6], 5 → 2
15 | [1,3,5,6], 2 → 1
16 | [1,3,5,6], 7 → 4
17 | [1,3,5,6], 0 → 0
18 |
19 | Inspired by @ouchxp at https://leetcode.com/discuss/8869/simple-binary-search-solution
20 |
21 | */
22 |
23 | import Foundation
24 |
25 | struct Medium_035_Search_Insert_Position {
26 | static func searchInsert(nums: [Int], target: Int) -> Int {
27 | var low: Int = 0
28 | var high: Int = nums.count - 1
29 | while low <= high {
30 | let mid: Int = low + (high - low)/2
31 | if target < nums[mid] {
32 | high = mid - 1
33 | } else if target > nums[mid] {
34 | low = mid + 1
35 | } else {
36 | return mid
37 | }
38 | }
39 | return low
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_039_Combination_Sum.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/combination-sum/
4 |
5 | #39 Combination Sum
6 |
7 | Level: medium
8 |
9 | Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
10 |
11 | The same repeated number may be chosen from C unlimited number of times.
12 |
13 | Note:
14 | All numbers (including target) will be positive integers.
15 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
16 | The solution set must not contain duplicate combinations.
17 | For example, given candidate set 2,3,6,7 and target 7,
18 | A solution set is:
19 | [7]
20 | [2, 2, 3]
21 |
22 | Inspired by @dylan_yu at https://leetcode.com/discuss/10141/a-solution-avoid-using-set
23 |
24 | */
25 |
26 | import Foundation
27 |
28 | struct Medium_039_Combination_Sum {
29 | private static func recurse(list: [Int], target: Int, candidates: [Int], index: Int, result: inout [[Int]]) {
30 | if target == 0 {
31 | result.append(list)
32 | return
33 | }
34 | for i in index ..< candidates.count {
35 | let newTarget: Int = target - candidates[i]
36 | if newTarget >= 0 {
37 | var copy: [Int] = Array(list)
38 | copy.append(candidates[i])
39 | recurse(list: copy, target: newTarget, candidates: candidates, index: i, result: &result)
40 | } else {
41 | break
42 | }
43 | }
44 | }
45 | static func combinationSum(candidates cdts: [Int], target: Int) -> [[Int]] {
46 | var candidates = cdts
47 | var result: [[Int]] = []
48 | candidates.sort {$0 < $1}
49 | recurse(list: [Int](), target: target, candidates: candidates, index: 0, result: &result)
50 | return result
51 | }
52 | }
53 |
54 |
55 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_040_Combination_Sum_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/combination-sum-ii/
4 |
5 | #40 Combination Sum II
6 |
7 | Level: medium
8 |
9 | Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
10 |
11 | Each number in C may only be used once in the combination.
12 |
13 | Note:
14 | All numbers (including target) will be positive integers.
15 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
16 | The solution set must not contain duplicate combinations.
17 | For example, given candidate set 10,1,2,7,6,1,5 and target 8,
18 | A solution set is:
19 | [1, 7]
20 | [1, 2, 5]
21 | [2, 6]
22 | [1, 1, 6]
23 |
24 | Inspired by @dylan_yu at https://leetcode.com/discuss/10141/a-solution-avoid-using-set (the same works for both #39 and #40)
25 |
26 | */
27 |
28 | import Foundation
29 |
30 | struct Medium_040_Combination_Sum_II {
31 | private static func recurse(list: [Int], target: Int, candidates: [Int], index: Int, result: inout [[Int]]) {
32 | if target == 0 {
33 | result.append(list)
34 | return
35 | }
36 | var ii = index - 1
37 | for i in index.. ii {
39 | let newTarget: Int = target - candidates[i]
40 | if newTarget >= 0 {
41 | var copy: [Int] = Array(list)
42 | copy.append(candidates[i])
43 | recurse(list: copy, target: newTarget, candidates: candidates, index: i+1, result: &result)
44 | ii = i
45 | while ii+1 < candidates.count && candidates[ii+1] == candidates[ii] {
46 | ii += 1
47 | }
48 | } else {
49 | break
50 | }
51 | }
52 | }
53 | }
54 | static func combinationSum(candidates c: [Int], target: Int) -> [[Int]] {
55 | var candidates = c
56 | var result: [[Int]] = []
57 | candidates.sort {$0 < $1}
58 | recurse(list: [Int](), target: target, candidates: candidates, index: 0, result: &result)
59 | return result
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_043_Multiply_Strings.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/multiply-strings/
4 |
5 | #43 Multiply Strings
6 |
7 | Level: medium
8 |
9 | Given two numbers represented as strings, return multiplication of the numbers as a string.
10 |
11 | Note: The numbers can be arbitrarily large and are non-negative.
12 |
13 | Inspired by @ChiangKaiShrek at https://leetcode.com/discuss/26602/brief-c-solution-using-only-strings-and-without-reversal
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | private extension String {
20 | subscript (index: Int) -> Character {
21 | return self[self.index(self.startIndex, offsetBy: index)]
22 | }
23 | }
24 |
25 | struct Medium_043_Multiply_Strings {
26 | static func multiply(num1: String, num2: String) -> String {
27 | var sum = Array(repeating: "0", count: num1.count+num2.count)
28 | let dict: [Character: Int] = [
29 | "0": 0,
30 | "1": 1,
31 | "2": 2,
32 | "3": 3,
33 | "4": 4,
34 | "5": 5,
35 | "6": 6,
36 | "7": 7,
37 | "8": 8,
38 | "9": 9,
39 | ]
40 | for i in (0 ... num1.count - 1).reversed() {
41 | var carry = 0
42 | for j in (0 ... num2.count - 1).reversed() {
43 | let tmp: Int = dict[sum[i + j + 1]]! + dict[num1[i]]! * dict[num2[j]]! + carry;
44 | sum[i + j + 1] = Character("\(tmp % 10)")
45 | carry = tmp / 10;
46 | }
47 | sum[i] = Character("\(dict[sum[i]]! + carry)")
48 | }
49 | for i in (0 ... sum.count - 1).reversed() {
50 | if sum[i] != "0" {
51 | return String(sum[0...i])
52 | }
53 | }
54 | return "0"
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_046_Permutations.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/permutations/
4 |
5 | #46 Permutations
6 |
7 | Level: medium
8 |
9 | Given a collection of numbers, return all possible permutations.
10 |
11 | For example,
12 | [1,2,3] have the following permutations:
13 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
14 |
15 | Inspired by @xiaohui7 at https://leetcode.com/discuss/18212/my-elegant-recursive-c-solution-with-inline-explanation
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | struct Medium_046_Permutations {
22 | private static func permuteRecursive(nums n: [Int], begin: Int, result: inout [[Int]]) {
23 | var nums = n
24 | if begin >= nums.count {
25 | result.append(nums)
26 | return
27 | }
28 | for i in begin.. [[Int]] {
35 | var result = [[Int]]()
36 | permuteRecursive(nums: nums, begin: 0, result: &result)
37 | return result
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_048_Rotate_Image.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/rotate-image/
4 |
5 | #48 Rotate Image
6 |
7 | Level: medium
8 |
9 | You are given an n x n 2D matrix representing an image.
10 |
11 | Rotate the image by 90 degrees (clockwise).
12 |
13 | Follow up:
14 | Could you do this in-place?
15 |
16 | Inspired by @shichaotan at https://leetcode.com/discuss/20589/a-common-method-to-rotate-the-image
17 |
18 | */
19 |
20 | import Foundation
21 |
22 | struct Medium_048_Rotate_Image {
23 | static func rotate(_ matrix: inout [[Int]]) {
24 | let n = matrix.count
25 | for i in 0 ..< n/2 {
26 | matrix.swapAt(i, n-1-i)
27 | }
28 | for i in 0 ..< n {
29 | for j in i+1 ..< n {
30 | let tmp = matrix[i][j]
31 | matrix[i][j] = matrix[j][i]
32 | matrix[j][i] = tmp
33 | }
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_049_Anagrams.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/anagrams/
4 |
5 | #49 Anagrams
6 |
7 | Level: medium
8 |
9 | Given an array of strings, group anagrams together.
10 |
11 | For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
12 | Return:
13 |
14 | [
15 | ["ate", "eat","tea"],
16 | ["nat","tan"],
17 | ["bat"]
18 | ]
19 |
20 | Note: All inputs will be in lower-case.
21 |
22 | Inspired by @zxyperfect at https://leetcode.com/discuss/18664/sharing-my-very-concise-solution-with-explanation
23 |
24 | */
25 |
26 | import Foundation
27 |
28 | struct Medium_049_Anagrams {
29 | private static func helper(_ str: String) -> String {
30 | var arr = Array(str)
31 | arr.sort()
32 | return String(arr)
33 | }
34 | static func anagrams(_ strings: [String]) -> [[String]] {
35 | var dict: [String: [String]] = [:]
36 | for s in strings {
37 | let sortedS = helper(s)
38 | var arr = dict[sortedS]
39 | if let _ = arr {
40 | arr!.append(s)
41 | } else {
42 | arr = [s]
43 | }
44 | dict[sortedS] = arr!
45 | }
46 | return Array(dict.values)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_050_Pow_X_N.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/powx-n/
4 |
5 | #50 Pow(x, n)
6 |
7 | Level: medium
8 |
9 | Implement pow(x, n).
10 |
11 | Inspired by @pei heng at https://leetcode.com/discuss/17005/short-and-easy-to-understand-solution
12 |
13 | */
14 |
15 | import Foundation
16 |
17 | struct Medium_050_Pow_X_N {
18 | static func myPow(x arg0: Double, n arg1: Int) -> Double {
19 | var x = arg0
20 | var n = arg1
21 | if n == 0 {
22 | return 1;
23 | }
24 | if n < 0 {
25 | n = -n;
26 | x = 1/x;
27 | }
28 | return ( n % 2 == 0) ? myPow(x: x*x, n: n/2) : x * myPow(x: x*x, n: n/2);
29 | }
30 | }
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_053_Maximum_Subarray.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/maximum-subarray/
4 |
5 | #53 Maximum Subarray
6 |
7 | Level: medium
8 |
9 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
10 |
11 | For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
12 | the contiguous subarray [4,−1,2,1] has the largest sum = 6.
13 |
14 | Inspired by @john6 at https://leetcode.com/discuss/1832/ive-idea-stucked-the-exception-situation-could-somebody-help
15 |
16 | */
17 |
18 | import Foundation
19 |
20 | struct Medium_053_Maximum_Subarray {
21 | static func maxSubArray(_ n: [Int]) -> Int {
22 | let nums = n
23 | var best = nums[0];
24 | var current = nums[0];
25 |
26 | for i in 1.. Bool {
29 | if rBegin > rEnd { return false }
30 | if cBegin > cEnd { return false }
31 | return true
32 | }
33 | static func spiralOrder(_ matrix: [[Int]]) -> [Int] {
34 | let m = matrix.count
35 | if m == 0 { return [] }
36 | let n = matrix[0].count
37 | if n == 0 { return [] }
38 | var result = [Int]()
39 | var rBegin = 0, cBegin = 0
40 | var rEnd = m - 1
41 | var cEnd = n - 1
42 | while rBegin <= rEnd && cBegin <= cEnd {
43 | for i in cBegin ... cEnd { result.append(matrix[rBegin][i]) }
44 | rBegin += 1
45 | if validate(rBegin, rEnd, cBegin, cEnd) == true {
46 | for i in rBegin ... rEnd { result.append(matrix[i][cEnd]) }
47 | }
48 | cEnd -= 1
49 | if validate(rBegin, rEnd, cBegin, cEnd) == true {
50 | for i in (cBegin ... cEnd).reversed() { result.append(matrix[rEnd][i]) }
51 | }
52 | rEnd -= 1
53 | if validate(rBegin, rEnd, cBegin, cEnd) == true {
54 | for i in (rBegin ... rEnd).reversed() { result.append(matrix[i][cBegin]) }
55 | }
56 | cBegin += 1
57 | }
58 | return result
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_055_Jump_Game.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/jump-game/
4 |
5 | #55 Jump Game
6 |
7 | Level: medium
8 |
9 | Given an array of non-negative integers, you are initially positioned at the first index of the array.
10 |
11 | Each element in the array represents your maximum jump length at that position.
12 |
13 | Determine if you are able to reach the last index.
14 |
15 | For example:
16 | A = [2,3,1,1,4], return true.
17 |
18 | A = [3,2,1,0,4], return false.
19 |
20 | */
21 |
22 | import Foundation
23 |
24 | struct Medium_055_Jump_Game {
25 | static func canJump(_ nums: [Int]) -> Bool {
26 | if nums.count == 0 { return false }
27 | var curr = nums[0]
28 | for i in 1 ..< nums.count {
29 | if curr == 0 { return false }
30 | curr = max(curr - 1, nums[i])
31 | }
32 | return true
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_059_Spiral_Matrix_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/spiral-matrix-ii/
4 |
5 | #59 Spiral Matrix II
6 |
7 | Level: medium
8 |
9 | Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
10 |
11 | For example,
12 | Given n = 3,
13 |
14 | You should return the following matrix:
15 | [
16 | [ 1, 2, 3 ],
17 | [ 8, 9, 4 ],
18 | [ 7, 6, 5 ]
19 | ]
20 |
21 | Inspired by @yike at https://leetcode.com/discuss/21677/simple-c-solution-with-explaination
22 |
23 | */
24 |
25 | import Foundation
26 |
27 | struct Medium_059_Spiral_Matrix_II {
28 | static func generateMatrix(_ n: Int) -> [[Int]] {
29 | var res = Array<[Int]>(repeating: Array(repeating: 0, count: n), count: n)
30 | var k = 1
31 | var i = 0
32 | while k <= n * n {
33 | var j = i
34 | while j < n - i {
35 | res[i][j] = k
36 | j += 1
37 | k += 1
38 | }
39 | j = i + 1
40 | while j < n - i {
41 | res[j][n-i-1] = k
42 | j += 1
43 | k += 1
44 | }
45 | j = n - i - 2
46 | while j > i {
47 | res[n-i-1][j] = k
48 | j -= 1
49 | k += 1
50 | }
51 | j = n - i - 1
52 | while j > i {
53 | res[j][i] = k
54 | j -= 1
55 | k += 1
56 | }
57 | i += 1
58 | }
59 | return res
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_060_Permutation_Sequence.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/permutation-sequence/
4 |
5 | #60 Permutation Sequence
6 |
7 | Level: medium
8 |
9 | The set [1,2,3,…,n] contains a total of n! unique permutations.
10 |
11 | By listing and labeling all of the permutations in order,
12 | We get the following sequence (ie, for n = 3):
13 |
14 | "123"
15 | "132"
16 | "213"
17 | "231"
18 | "312"
19 | "321"
20 | Given n and k, return the kth permutation sequence.
21 |
22 | Note: Given n will be between 1 and 9 inclusive.
23 |
24 | Inspired by @lucastan at https://leetcode.com/discuss/11023/most-concise-c-solution-minimal-memory-required
25 |
26 | */
27 |
28 | import Foundation
29 |
30 | struct Medium_060_Permutation_Sequence {
31 | static func getPermutation(n: Int, k arg: Int) -> String {
32 | var k = arg
33 | var j: Int
34 | var f: Int = 1
35 | var s = [Character](repeating: "0", count: n)
36 | let map: [Int: Character] = [1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9"]
37 | for i in 1...n {
38 | f *= i
39 | s[i-1] = map[i]!
40 | }
41 | k -= 1
42 | for i in 0.. i {
47 | for m in (i+1...j).reversed() {
48 | s[m] = s[m-1]
49 | }
50 | }
51 | k %= f
52 | s[i] = c
53 | }
54 | return String(s)
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_061_Rotate_List.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/rotate-list/
4 |
5 | #62 Rotate List
6 |
7 | Level: medium
8 |
9 | Given a list, rotate the list to the right by k places, where k is non-negative.
10 |
11 | For example:
12 | Given 1->2->3->4->5->NULL and k = 2,
13 | return 4->5->1->2->3->NULL.
14 |
15 | Inspired by @reeclapple at https://leetcode.com/discuss/9533/share-my-java-solution-with-explanation
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | class Medium_061_Rotate_List {
22 | class Node {
23 | var value: Int?
24 | var next: Node?
25 | }
26 | class func rotateRight(head: Node?, k: Int) -> Node? {
27 | if head == nil || head?.next == nil {
28 | return head;
29 | }
30 | let dummy: Node = Node()
31 | dummy.next = head
32 | var fast: Node? = dummy
33 | var slow: Node? = dummy
34 | var i = 0
35 | while fast?.next != nil {
36 | fast = fast?.next
37 | i += 1
38 | }
39 | let count = i - k % i
40 | for _ in 0 ..< count {
41 | slow = slow?.next
42 | }
43 | fast?.next = dummy.next
44 | dummy.next = slow?.next
45 | slow?.next = nil
46 | return dummy.next
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_062_Unique_Paths.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/unique-paths/
4 |
5 | #62 Unique Paths
6 |
7 | Level: medium
8 |
9 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
10 |
11 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
12 |
13 | How many possible unique paths are there?
14 |
15 | Inspired by @d40a at https://leetcode.com/discuss/9110/my-ac-solution-using-formula
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | struct Medium_062_Unique_Paths {
22 | static func uniquePaths(m: Int, n: Int) -> Int {
23 | let N = n + m - 2
24 | let k = min(m - 1, n - 1)
25 | var res = 1
26 | for i in 1 ... k {
27 | res = res * (N - k + i) / i;
28 | }
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_063_Unique_Paths_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/unique-paths-ii/
4 |
5 | #63 Unique Paths II
6 |
7 | Level: medium
8 |
9 | Follow up for "Unique Paths":
10 |
11 | Now consider if some obstacles are added to the grids. How many unique paths would there be?
12 |
13 | An obstacle and empty space is marked as 1 and 0 respectively in the grid.
14 |
15 | For example,
16 | There is one obstacle in the middle of a 3x3 grid as illustrated below.
17 |
18 | [
19 | [0,0,0],
20 | [0,1,0],
21 | [0,0,0]
22 | ]
23 | The total number of unique paths is 2.
24 |
25 | Note: m and n will be at most 100.
26 |
27 | Inspired by @vvelrath@buffalo.edu at https://leetcode.com/discuss/15756/java-solution-using-dynamic-programming-o-1-space
28 |
29 | */
30 |
31 | import Foundation
32 |
33 | struct Medium_063_Unique_Paths_II {
34 | static func uniquePathsWithObstacles(_ og: [[Int]]) -> Int {
35 | var obstacleGrid = og
36 | if obstacleGrid.count == 0 {
37 | return 0
38 | }
39 | if obstacleGrid[0].count == 0 {
40 | return 0
41 | }
42 | let rows = obstacleGrid.count
43 | let cols = obstacleGrid[0].count
44 |
45 | for i in 0 ..< rows {
46 | for j in 0 ..< cols {
47 | if obstacleGrid[i][j] == 1 {
48 | obstacleGrid[i][j] = 0
49 | } else if i == 0 && j == 0 {
50 | obstacleGrid[i][j] = 1
51 | } else if i == 0 {
52 | obstacleGrid[i][j] = obstacleGrid[i][j-1] * 1
53 | } else if j == 0 {
54 | obstacleGrid[i][j] = obstacleGrid[i-1][j] * 1
55 | } else {
56 | obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
57 | }
58 | }
59 | }
60 |
61 | return obstacleGrid[rows-1][cols-1];
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_064_Minimum_Path_Sum.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/minimum-path-sum/
4 |
5 | #64 Minimum Path Sum
6 |
7 | Level: medium
8 |
9 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
10 |
11 | Note: You can only move either down or right at any point in time.
12 |
13 | Inspired by @wdj0xda at https://leetcode.com/discuss/17111/my-java-solution-using-dp-and-no-extra-space
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | struct Medium_064_Minimum_Path_Sum {
20 | static func minPathSum(_ g: [[Int]]) -> Int {
21 | var grid = g
22 | if grid.count == 0 {
23 | return 0
24 | }
25 | let rows = grid.count
26 | let cols = grid[0].count
27 |
28 | for i in 0.. Int {
21 | var ans: Int64 = 0
22 | var bit: Int64 = 1 << 16
23 | while bit > 0 {
24 | ans |= bit
25 | if ans * ans > Int64(x) {
26 | ans ^= bit
27 | }
28 | bit >>= 1
29 | }
30 | return Int(ans)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_071_Simplify_Path.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/simplify-path/
4 |
5 | #71 Simplify Path
6 |
7 | Level: medium
8 |
9 | Given an absolute path for a file (Unix-style), simplify it.
10 |
11 | For example,
12 | path = "/home/", => "/home"
13 | path = "/a/./b/../../c/", => "/c"
14 |
15 | Corner Cases:
16 | Did you consider the case where path = "/../"?
17 | In this case, you should return "/".
18 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
19 | In this case, you should ignore redundant slashes and return "/home/foo".
20 |
21 | Inspired by @monaziyi at https://leetcode.com/discuss/24939/c-10-lines-solution
22 |
23 | */
24 |
25 | import Foundation
26 |
27 | struct Medium_071_Simplify_Path {
28 | static func simplifyPath(_ path: String) -> String {
29 | let arr = path.split{ $0=="/" }.map(String.init)
30 | var stack = [String]()
31 | for s in arr {
32 | if s == "" || s == "." { continue }
33 | if s == ".." { _ = stack.popLast(); continue; }
34 | stack.append(s)
35 | }
36 | return stack.isEmpty ? "/" : "/" + stack.joined(separator:"/")
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_073_Set_Matrix_Zeroes.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/set-matrix-zeroes/
4 |
5 | #73 Set Matrix Zeroes
6 |
7 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
8 |
9 | Follow up:
10 | Did you use extra space?
11 | A straight forward solution using O(mn) space is probably a bad idea.
12 | A simple improvement uses O(m + n) space, but still not the best solution.
13 | Could you devise a constant space solution?
14 |
15 | Inspired by @mzchen at https://leetcode.com/discuss/15997/any-shortest-o-1-space-solution
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | struct Medium_073_Set_Matrix_Zeroes {
22 | static func setZeros(_ matrix: inout [[Int]]) {
23 | var col0 = 1
24 | let rows = matrix.count
25 | let cols = matrix[0].count
26 | for i in stride(from: 0, to: rows, by: 1) {
27 | if matrix[i][0] == 0 {
28 | col0 = 0
29 | }
30 | for j in stride(from: 1, to: cols, by: 1) {
31 | if matrix[i][j] == 0 {
32 | matrix[i][0] = 0
33 | matrix[0][j] = 0
34 | }
35 | }
36 | }
37 | for i in stride(from: rows-1, through: 0, by: -1) {
38 | for j in stride(from: cols-1, through: 0, by: -1) {
39 | if matrix[i][0] == 0 || matrix[0][j] == 0 {
40 | matrix[i][j] = 0
41 | }
42 | }
43 | if col0 == 0 {
44 | matrix[i][0] = 0
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_074_Search_A_2D_Matrix.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/search-a-2d-matrix/
4 |
5 | #74 Search a 2D Matrix
6 |
7 | Level: medium
8 |
9 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
10 |
11 | Integers in each row are sorted from left to right.
12 | The first integer of each row is greater than the last integer of the previous row.
13 | For example,
14 |
15 | Consider the following matrix:
16 |
17 | [
18 | [1, 3, 5, 7],
19 | [10, 11, 16, 20],
20 | [23, 30, 34, 50]
21 | ]
22 | Given target = 3, return true.
23 |
24 | Inspired by @vaputa at https://leetcode.com/discuss/10735/dont-treat-it-as-a-2d-matrix-just-treat-it-as-a-sorted-list
25 |
26 | */
27 |
28 | import Foundation
29 |
30 | struct Medium_074_Search_A_2D_Matrix {
31 | static func searchMatrix(matrix: [[Int]], target: Int) -> Bool {
32 | let m = matrix.count
33 | guard m > 0 else { return false }
34 | let n = matrix[0].count
35 | guard n > 0 else { return false }
36 | var lo = 0, hi = m * n - 1
37 | while lo < hi {
38 | let mid = (lo+hi)/2
39 | let r = mid/n
40 | let c = mid%n
41 | let midV = matrix[r][c]
42 | if target == midV { return true }
43 | else if target < midV { hi = mid - 1 }
44 | else { lo = mid + 1}
45 | }
46 | let r = lo/n, c = lo%n, midV = matrix[r][c]
47 | return midV == target
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_075_Sort_Colors.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/sort-colors/
4 |
5 | #75 Sort Colors
6 |
7 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
8 |
9 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
10 |
11 | Note:
12 | You are not suppose to use the library's sort function for this problem.
13 |
14 | click to show follow up.
15 |
16 | Follow up:
17 | A rather straight forward solution is a two-pass algorithm using counting sort.
18 | First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
19 |
20 | Could you come up with an one-pass algorithm using only constant space?
21 |
22 | Inspired by @xianlei at https://leetcode.com/discuss/1827/anyone-with-one-pass-and-constant-space-solution
23 |
24 | */
25 |
26 | import Foundation
27 |
28 | struct Medium_075_Sort_Colors {
29 | static func sortColors(_ nums: inout [Int]) {
30 | var red = -1
31 | var white = -1
32 | var blue = -1
33 | for i in 0 ..< nums.count {
34 | if nums[i] == 0 {
35 | blue += 1
36 | white += 1
37 | red += 1
38 | nums[blue] = 2
39 | nums[white] = 1
40 | nums[red] = 0
41 | } else if nums[i] == 1 {
42 | blue += 1
43 | white += 1
44 | nums[blue] = 2
45 | nums[white] = 1
46 | } else {
47 | blue += 1
48 | nums[blue] = 2
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_077_Combinations.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/combinations/
4 |
5 | #77 Combinations
6 |
7 | Level: medium
8 |
9 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
10 |
11 | For example,
12 | If n = 4 and k = 2, a solution is:
13 |
14 | [
15 | [2,4],
16 | [3,4],
17 | [2,3],
18 | [1,2],
19 | [1,3],
20 | [1,4],
21 | ]
22 |
23 | Inspired by @reeclapple at https://leetcode.com/discuss/5913/whats-the-best-solution and @nangao at https://leetcode.com/discuss/12915/my-shortest-c-solution-using-dfs
24 |
25 | */
26 |
27 | import Foundation
28 |
29 | struct Medium_077_Combinations {
30 | static func combine(n: Int, k: Int) -> [[Int]] {
31 | var queue: [[Int]] = []
32 | var summary: [[Int]] = []
33 | for i in 1...n {
34 | var list: [Int] = []
35 | list.append(i)
36 | queue.append(list)
37 | }
38 | while queue.isEmpty == false {
39 | let list = queue.removeFirst()
40 | if list.count == k {
41 | summary.append(list)
42 | } else {
43 | if list.last! + 1 <= n {
44 | for i in list.last! + 1...n {
45 | var nextList: [Int] = [Int](list)
46 | nextList.append(i)
47 | queue.append(nextList)
48 | }
49 | }
50 | }
51 | }
52 | return summary
53 | }
54 | static func combine_recursion_helper(res: inout [[Int]], tmp: inout [Int], start: Int, num: Int, n: Int, k: Int) {
55 | if num == k {
56 | res.append(tmp)
57 | return
58 | }
59 | for i in start.. [[Int]] {
66 | var res: [[Int]] = []
67 | if n < k {
68 | return res
69 | }
70 | var tmp: [Int] = []
71 | combine_recursion_helper(res: &res, tmp: &tmp, start: 0, num: 0, n: n, k: k)
72 | return res
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_078_Subsets.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/subsets/
4 |
5 | #78 Subsets
6 |
7 | Level: medium
8 |
9 | Given a set of distinct integers, nums, return all possible subsets.
10 |
11 | Note:
12 | Elements in a subset must be in non-descending order.
13 | The solution set must not contain duplicate subsets.
14 | For example,
15 | If nums = [1,2,3], a solution is:
16 |
17 | [
18 | [3],
19 | [1],
20 | [2],
21 | [1,2,3],
22 | [1,3],
23 | [2,3],
24 | [1,2],
25 | []
26 | ]
27 |
28 | Inspired by @thumike at https://leetcode.com/discuss/9213/my-solution-using-bit-manipulation
29 |
30 | */
31 |
32 | import Foundation
33 |
34 | struct Medium_078_Subsets {
35 | static func subsets(_ n: [Int]) -> [[Int]] {
36 | var nums = n
37 | nums.sort {$0 < $1}
38 | let elemNum = nums.count
39 | let subsetNum = Int(pow(2.0, Double(elemNum)))
40 | var subsets: [[Int]] = [[Int]](repeating: [], count: subsetNum)
41 | for i in 0..> i) & 1) != 0 {
44 | subsets[j].append(nums[i])
45 | }
46 | }
47 | }
48 | return subsets
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_079_Word_Search.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/word-search/
4 |
5 | #79 Word Search
6 |
7 | Level: medium
8 |
9 | Given a 2D board and a word, find if the word exists in the grid.
10 |
11 | The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
12 |
13 | For example,
14 | Given board =
15 |
16 | [
17 | ["ABCE"],
18 | ["SFCS"],
19 | ["ADEE"]
20 | ]
21 | word = "ABCCED", -> returns true,
22 | word = "SEE", -> returns true,
23 | word = "ABCB", -> returns false.
24 |
25 | Inspired by @pavel-shlyk at https://leetcode.com/discuss/23165/accepted-very-short-java-solution-no-additional-space
26 |
27 | */
28 |
29 | import Foundation
30 |
31 | struct Medium_079_Word_Search {
32 | static func exist(_ b: [[Character]], word: String) -> Bool {
33 | var board = b
34 | for x in 0.. Bool {
44 | if i == word.count {
45 | return true
46 | }
47 | if x < 0 || y < 0 || x == board.count || y == board[x].count {
48 | return false
49 | }
50 | let wArr = [Character](word)
51 | if board[x][y] != wArr[i] {
52 | return false
53 | }
54 |
55 | let tmp: Character = board[x][y]
56 | board[x][y] = "_"
57 | let exist: Bool = exist_recursion_helper(board: &board, x: x, y: y+1, word: word, i: i+1)
58 | || exist_recursion_helper(board: &board, x: x, y: y-1, word: word, i: i+1)
59 | || exist_recursion_helper(board: &board, x: x-1, y: y, word: word, i: i+1)
60 | || exist_recursion_helper(board: &board, x: x+1, y: y, word: word, i: i+1)
61 | board[x][y] = tmp
62 | return exist
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_080_Remove_Duplicates_From_Sorted_Array_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
4 |
5 | #80 Remove Duplicates from Sorted Array II
6 |
7 | Level: medium
8 |
9 | Follow up for "Remove Duplicates":
10 | What if duplicates are allowed at most twice?
11 |
12 | For example,
13 | Given sorted array nums = [1,1,1,2,2,3],
14 |
15 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
16 |
17 | Inspired by @dragonmigo at https://leetcode.com/discuss/2754/is-it-possible-to-solve-this-question-in-place
18 |
19 | */
20 |
21 | import Foundation
22 |
23 | struct Medium_080_Remove_Duplicates_From_Sorted_Array_II {
24 | static func removeDuplicates(_ nums: inout [Int]) -> Int {
25 | guard nums.count > 0 else { return 0 }
26 | var curr = 0, count = 0, prev = Int.min
27 | for i in 0.. Bool {
24 | guard nums.count > 0 else { return false }
25 | var lo = 0, hi = nums.count - 1
26 | while lo < hi {
27 | let mid = (lo + hi)/2
28 | if nums[mid] == target { return true }
29 | if nums[lo] < nums[mid] {
30 | if target < nums[mid] && target >= nums[lo] { hi = mid - 1 }
31 | else { lo = mid + 1 }
32 | } else if nums[lo] > nums[mid] {
33 | if target > nums[mid] && target <= nums[hi] { lo = mid + 1 }
34 | else { hi = mid - 1 }
35 | } else { lo += 1 }
36 | }
37 | return nums[lo] == target
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_082_Remove_Duplicates_From_Sorted_List_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
4 |
5 | #82 Remove Duplicates from Sorted List II
6 |
7 | Level: medium
8 |
9 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
10 |
11 | For example,
12 | Given 1->2->3->3->4->4->5, return 1->2->5.
13 | Given 1->1->1->2->3, return 2->3.
14 |
15 | Inspired by @snowfish at https://leetcode.com/discuss/12724/my-accepted-java-code
16 |
17 | */
18 |
19 | import Foundation
20 |
21 | class Medium_082_Remove_Duplicates_From_Sorted_List_II {
22 | class Node {
23 | var value: Int
24 | var next: Node?
25 | init(value: Int, next: Node?) {
26 | self.value = value
27 | self.next = next
28 | }
29 | }
30 | class func deleteDuplicates(_ head: Node?) -> Node? {
31 | if head == nil {
32 | return nil
33 | }
34 | let fakeHead = Node(value: 0, next: nil)
35 | fakeHead.next = head
36 | var prev: Node? = fakeHead
37 | var curr: Node? = head
38 | while curr != nil {
39 | while curr?.next != nil && curr?.value == curr?.next?.value {
40 | curr = curr?.next
41 | }
42 | if prev?.next === curr {
43 | prev = prev?.next
44 | } else {
45 | prev?.next = curr?.next
46 | }
47 | curr = curr?.next
48 | }
49 | return fakeHead.next
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_086_Partition_List.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/partition-list/
4 |
5 | #86 Partition List
6 |
7 | Level: medium
8 |
9 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
10 |
11 | You should preserve the original relative order of the nodes in each of the two partitions.
12 |
13 | For example,
14 | Given 1->4->3->2->5->2 and x = 3,
15 | return 1->2->2->4->3->5.
16 |
17 | Inspired by @shichaotan at https://leetcode.com/discuss/21032/very-concise-one-pass-solution
18 |
19 | */
20 |
21 | import Foundation
22 |
23 | class Medium_086_Partition_List {
24 | class Node {
25 | var value: Int
26 | var next: Node?
27 | init(value: Int, next: Node?) {
28 | self.value = value
29 | self.next = next
30 | }
31 | }
32 | class func partition(head h: Node?, x: Int) -> Node? {
33 | var head = h
34 | let sentinelA: Node? = Node(value: 0, next: nil)
35 | let sentinelB: Node? = Node(value: 0, next: nil)
36 | var pA: Node? = sentinelA
37 | var pB: Node? = sentinelB
38 | while head != nil {
39 | if (head?.value)! < x {
40 | pA?.next = head
41 | pA = pA?.next
42 | } else {
43 | pB?.next = head
44 | pB = pB?.next
45 | }
46 | head = head?.next
47 | }
48 | pB?.next = nil
49 | pA?.next = sentinelB?.next
50 | return sentinelA?.next
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_089_Gray_Code.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/gray-code/
4 |
5 | #89 Gray Code
6 |
7 | Level: medium
8 |
9 | The gray code is a binary numeral system where two successive values differ in only one bit.
10 |
11 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
12 |
13 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
14 |
15 | 00 - 0
16 | 01 - 1
17 | 11 - 3
18 | 10 - 2
19 |
20 | Note:
21 | For a given n, a gray code sequence is not uniquely defined.
22 |
23 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
24 |
25 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
26 |
27 | Inspired by @jinrf at https://discuss.leetcode.com/topic/8557/an-accepted-three-line-solution-in-java
28 |
29 | */
30 |
31 | import Foundation
32 |
33 | struct Medium_089_Gray_Code {
34 | static func grayCode(_ n: Int) -> [Int] {
35 | var arr: [Int] = []
36 | for i in 0 ..< 1<>1)
38 | }
39 | return arr
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_090_Subsets_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/subsets-ii/
4 |
5 | #90 Subsets II
6 |
7 | Given a collection of integers that might contain duplicates, nums, return all possible subsets.
8 |
9 | Note:
10 | Elements in a subset must be in non-descending order.
11 | The solution set must not contain duplicate subsets.
12 | For example,
13 | If nums = [1,2,2], a solution is:
14 |
15 | [
16 | [2],
17 | [1],
18 | [1,2,2],
19 | [2,2],
20 | [1,2],
21 | []
22 | ]
23 |
24 | Inspired by @mathsam at https://leetcode.com/discuss/14902/c-solution-and-explanation
25 |
26 | */
27 |
28 | import Foundation
29 |
30 | struct Medium_090_Subsets_II {
31 | static func subsetsWithDup(_ n: [Int]) -> [[Int]] {
32 | var nums = n
33 | var result: [[Int]] = [[]]
34 | nums.sort()
35 | var i = 0
36 | for _ in 0 ..< nums.count{
37 | var count: Int = 0
38 | while count + i < nums.count && nums[count+i] == nums[i] {
39 | count += 1
40 | }
41 | let prevSize: Int = result.count
42 | for k in 0 ..< prevSize {
43 | var tmp: [Int] = result[k]
44 | for _ in 0 ..< count {
45 | tmp.append(nums[i])
46 | result.append(tmp)
47 | }
48 | }
49 | i += count
50 | }
51 | return result
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_091_Decode_Ways.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/decode-ways/
4 |
5 | #91 Decode Ways
6 |
7 | Level: medium
8 |
9 | A message containing letters from A-Z is being encoded to numbers using the following mapping:
10 |
11 | 'A' -> 1
12 | 'B' -> 2
13 | ...
14 | 'Z' -> 26
15 | Given an encoded message containing digits, determine the total number of ways to decode it.
16 |
17 | For example,
18 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
19 |
20 | The number of ways decoding "12" is 2.
21 |
22 | Inspired by @manky at https://leetcode.com/discuss/8527/dp-solution-java-for-reference
23 |
24 | */
25 |
26 | import Foundation
27 |
28 | struct Medium_091_Decode_Ways {
29 | static func numDecodings(_ s: String) -> Int {
30 | let len = s.count
31 | if len == 0 { return 0 }
32 | let arr = [Character](s)
33 | var dp = [Int](repeating: 0, count: len+1)
34 | dp[len] = 1
35 | dp[len-1] = (arr[len-1] == "0") ? 0 : 1
36 | for i in (0..2->3->4->5->NULL, m = 2 and n = 4,
13 |
14 | return 1->4->3->2->5->NULL.
15 |
16 | Note:
17 | Given m, n satisfy the following condition:
18 | 1 ≤ m ≤ n ≤ length of list.
19 |
20 | Inspired by @ardyadipta at https://leetcode.com/discuss/25580/simple-java-solution-with-clear-explanation
21 |
22 | */
23 |
24 | import Foundation
25 |
26 | class Medium_092_Reverse_Linked_List_II {
27 | class Node {
28 | var value: Int
29 | var next: Node?
30 | init(value: Int, next: Node?) {
31 | self.value = value
32 | self.next = next
33 | }
34 | }
35 | // t = O(N), s = O(1), one pass
36 | class func reverseBetween(_ head: Node?, m: Int, n: Int) -> Node? {
37 | if head == nil {
38 | return nil
39 | }
40 | let dummy: Node = Node(value: 0, next: head)
41 | var pre: Node? = dummy
42 | for _ in 0 ..< m-1 {
43 | pre = pre?.next
44 | }
45 | let start: Node? = pre?.next
46 | var then: Node? = start?.next
47 | for _ in 0 ..< n-m {
48 | start?.next = then?.next
49 | then?.next = pre?.next
50 | pre?.next = then
51 | then = start?.next
52 | }
53 | return dummy.next
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_093_Restore_IP_Addresses.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/restore-ip-addresses/
4 |
5 | #93 Restore IP Addresses
6 |
7 | Level: medium
8 |
9 | Given a string containing only digits, restore it by returning all possible valid IP address combinations.
10 |
11 | For example:
12 | Given "25525511135",
13 |
14 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
15 |
16 | Inspired by @fiona_mao at https://leetcode.com/discuss/12790/my-code-in-java
17 |
18 | */
19 |
20 | import Foundation
21 |
22 | struct Medium_093_Restore_IP_Addresses {
23 | // t = O(1), s = O(1)
24 | static func restoreIpAddresses(_ s: String) -> [String] {
25 | let chars = [Character](s)
26 | let len = chars.count
27 | guard len >= 4 else { return [] }
28 | var result = [String]()
29 | for i in 1...min(3, len-3) {
30 | for j in i...min(i+3, len-2) {
31 | for k in j...min(j+3, len-1) {
32 | let s0 = String(chars[0.. Bool {
47 | let chars = [Character](s)
48 | if chars.count > 1 && chars[0] == "0" { return false }
49 | let v = Int(s) ?? Int.max
50 | if v < 0 || v > 255 { return false }
51 | else { return true }
52 | }
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_095_Unique_Binary_Search_Trees_II.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/unique-binary-search-trees-ii/
4 |
5 | #95 Unique Binary Search Trees II
6 |
7 | Level: medium
8 |
9 | Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
10 |
11 | For example,
12 | Given n = 3, your program should return all 5 unique BST's shown below.
13 |
14 | 1 3 3 2 1
15 | \ / / / \ \
16 | 3 2 1 1 3 2
17 | / / \ \
18 | 2 1 2 3
19 |
20 | Inspired by @Jayanta at https://leetcode.com/discuss/10254/a-simple-recursive-solution
21 |
22 | */
23 |
24 | import Foundation
25 |
26 | class Medium_095_Unique_Binary_Search_Trees_II {
27 | class Node {
28 | var value: Int
29 | var left: Node?
30 | var right: Node?
31 | init(value: Int, left: Node?, right: Node?) {
32 | self.value = value
33 | self.left = left
34 | self.right = right
35 | }
36 | }
37 | private class func genTrees (start: Int, end: Int) -> [Node?] {
38 | var ret: [Node?] = []
39 | if start > end {
40 | ret.append(nil)
41 | return ret
42 | } else if start == end {
43 | ret.append(Node(value: start, left: nil, right: nil))
44 | return ret
45 | }
46 | var left: [Node?] = []
47 | var right: [Node?] = []
48 | for i in start ... end {
49 | left = genTrees(start: start, end: i - 1)
50 | right = genTrees(start: i + 1, end: end)
51 | for left_node in left {
52 | for right_node in right {
53 | let root = Node(value: i, left: left_node, right: right_node)
54 | ret.append(root)
55 | }
56 | }
57 | }
58 | return ret
59 | }
60 | // t = O(n^(n-1)) a.k.a Catalan Number, s = I've no idea
61 | class func generateTrees(_ n: Int) -> [Node?] {
62 | return genTrees(start: 1, end: n)
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_096_Unique_Binary_Search_Trees.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/unique-binary-search-trees/
4 |
5 | #96 Unique Binary Search Trees
6 |
7 | Level: medium
8 |
9 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
10 |
11 | For example,
12 | Given n = 3, there are a total of 5 unique BST's.
13 |
14 | 1 3 3 2 1
15 | \ / / / \ \
16 | 3 2 1 1 3 2
17 | / / \ \
18 | 2 1 2 3
19 |
20 | Inspired by @liaison at https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i
21 |
22 | */
23 |
24 | import Foundation
25 |
26 | class Medium_096_Unique_Binary_Search_Trees {
27 | // t=O(N^2), s=O(N)
28 | class func numTrees(_ n: Int) -> Int {
29 | var ret: [Int] = Array(repeating: 0, count: n+1)
30 | ret[0] = 1
31 | ret[1] = 1
32 | if 2 <= n {
33 | for i in 2 ... n {
34 | for j in 0 ..< i {
35 | ret[i] += ret[j] * ret[i-1-j]
36 | }
37 | }
38 | }
39 | return ret[n]
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Solutions/Solutions/Medium/Medium_098_Validate_Binary_Search_Tree.swift:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/validate-binary-search-tree/
4 |
5 | #98 Validate Binary Search Tree
6 |
7 | Given a binary tree, determine if it is a valid binary search tree (BST).
8 |
9 | Assume a BST is defined as follows:
10 |
11 | The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.
12 |
13 | Inspired by [@jakwings](https://leetcode.com/discuss/14886/order-traversal-please-rely-buggy-int_max-int_min-solutions)
14 |
15 | */
16 |
17 | import Foundation
18 |
19 | class Medium_098_Validate_Binary_Search_Tree {
20 | class Node {
21 | var left: Node?
22 | var right: Node?
23 | var value: Int
24 | init(value: Int, left: Node?, right: Node?) {
25 | self.value = value
26 | self.left = left
27 | self.right = right
28 | }
29 | }
30 | private class func isValidBSTRecursionHelper(curr: Node?, prev: inout Node?) -> Bool {
31 | if curr == nil {
32 | return true
33 | } else {
34 | if isValidBSTRecursionHelper(curr: curr!.left, prev: &prev) == false {
35 | return false
36 | }
37 | if prev != nil && prev!.value > curr!.value {
38 | return false
39 | }
40 | prev = curr
41 | return isValidBSTRecursionHelper(curr: curr!.right, prev: &prev)
42 | }
43 | }
44 | // t = O(N), average s = O(logN), worst s = O(N)
45 | class func isValidBST(_ root: Node?) -> Bool {
46 | var prev: Node? = nil
47 | return isValidBSTRecursionHelper(curr: root, prev: &prev)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Solutions/Solutions/ViewController.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 3/6/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | class ViewController: UIViewController {
12 |
13 | override func viewDidLoad() {
14 | super.viewDidLoad()
15 | // Do any additional setup after loading the view, typically from a nib.
16 | }
17 |
18 | override func didReceiveMemoryWarning() {
19 | super.didReceiveMemoryWarning()
20 | // Dispose of any resources that can be recreated.
21 | }
22 |
23 |
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | //
2 | // Use this file to import your target's public headers that you would like to expose to Swift.
3 | //
4 |
5 | #import "ObjC_Medium_001_Two_Sum.h"
6 | #import "ObjC_Medium_002_Add_Two_Numbers.h"
7 | #import "ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters.h"
8 | #import "ObjC_Medium_092_Reverse_Linked_List_II.h"
9 | #import "ObjC_Hard_004_Median_Of_Two_Sorted_Arrays.h"
10 | #import "ObjC_Medium_005_Longest_Palindromic_Substring.h"
11 | #import "ObjC_Medium_093_Restore_IP_Addresses.h"
12 | #import "ObjC_Medium_017_Letter_Combinations_Of_A_Phone_Number.h"
13 | #import "ObjC_Medium_094_Binary_Tree_Inorder_Traversal.h"
14 | #import "ObjC_Medium_095_Unique_Binary_Search_Trees_II.h"
15 | #import "ObjC_Medium_096_Unique_Binary_Search_Trees.h"
16 | #import "ObjC_Hard_097_Interleaving_String.h"
17 | #import "ObjC_Medium_098_Validate_Binary_Search_Tree.h"
18 | #import "ObjC_Hard_099_Recover_Binary_Search_Tree.h"
19 | #import "ObjC_Easy_100_Same_Tree.h"
20 | #import "ObjC_Easy_101_Symmetric_Tree.h"
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_006_ZigZag_Conversion_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_006_ZigZag_Conversion_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 3/6/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_006_ZigZag_Conversion_Test: XCTestCase, SolutionsTestCase {
12 |
13 | func test_001() {
14 | let input: [Any] = ["PAYPALISHIRING", 3]
15 | let expected: String = "PAHNAPLSIIGYIR"
16 | let result = Easy_006_ZigZag_Conversion.convert(s: input[0] as! String, nRows: input[1] as! Int)
17 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
18 | }
19 |
20 | func test_002() {
21 | let input: [Any] = ["PAYPALISHIRING", 1]
22 | let expected: String = "PAYPALISHIRING"
23 | let result = Easy_006_ZigZag_Conversion.convert(s: input[0] as! String, nRows: input[1] as! Int)
24 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
25 | }
26 |
27 | func test_003() {
28 | let input: [Any] = ["", 3]
29 | let expected: String = ""
30 | let result = Easy_006_ZigZag_Conversion.convert(s: input[0] as! String, nRows: input[1] as! Int)
31 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
32 | }
33 |
34 | func test_004() {
35 | /*
36 | P I N
37 | A L S I G
38 | Y A H R
39 | P I
40 | */
41 | let input: [Any] = ["PAYPALISHIRING", 4]
42 | let expected: String = "PINALSIGYAHRPI"
43 | let result = Easy_006_ZigZag_Conversion.convert(s: input[0] as! String, nRows: input[1] as! Int)
44 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
45 | }
46 | }
47 |
48 | /*
49 | "PAYPALISHIRING" -> "PAHNAPLSIIGYIR"
50 | */
51 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_013_Roman_To_Integer_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_013_Roman_To_Integer_Test.swift
3 | // Solutions
4 | //
5 | // Created by Wu, Di on 3/30/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_013_Roman_To_Integer_Test: XCTestCase, SolutionsTestCase {
12 |
13 |
14 | func test_001() {
15 | let input: String = "I"
16 | let expected: Int = 1
17 | let result: Int = Easy_013_Roman_To_Integer.romanToInt(s: input)
18 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
19 | }
20 | func test_002() {
21 | let input: String = "MMMCMXCIX"
22 | let expected: Int = 3999
23 | let result: Int = Easy_013_Roman_To_Integer.romanToInt(s: input)
24 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
25 | }
26 | }
27 |
28 | /*
29 | I => 1
30 | MMMCMXCIX => 3999
31 | */
32 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_027_Remove_Element_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_027_Remove_Element_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/7/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_027_Remove_Element_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [Any] = [[1, 2, 2, 3], 2]
14 | let expected: [Int] = [1, 3]
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [Any] = [[1, 2, 3], 4]
19 | let expected: [Int] = [1, 2, 3]
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: [Any] = [[], 4]
24 | let expected: [Int] = []
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_004() {
28 | let input: [Any] = [[1, 2, 2, 3, 6, 7, 6, 8, 1, 3, 2, 6], 6]
29 | let expected: [Int] = [1, 2, 2, 3, 7, 8, 1, 3, 2]
30 | asyncHelper(input: input, expected: expected)
31 | }
32 | func test_005() {
33 | let input: [Any] = [[1], 1]
34 | let expected: [Int] = []
35 | asyncHelper(input: input, expected: expected)
36 | }
37 | private func asyncHelper(input ipt: [Any], expected: [Int]) {
38 | let input = ipt
39 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
40 | serialQueue().async(execute: { () -> Void in
41 | var arr: [Int] = input[0] as! [Int]
42 | let elem: Int = input[1] as! Int
43 | let result: Int = Easy_027_Remove_Element.removeElement(arr: &arr, elem: elem)
44 | assertHelper(expected == Array(arr[0.. Void in
50 | if error != nil {
51 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_038_Count_And_Say_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_038_Count_And_Say_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/15/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_038_Count_And_Say_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: Int = 1
14 | let expected: String = "11"
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: Int = 8
19 | let expected: String = "31131211131221"
20 | asyncHelper(input: input, expected: expected)
21 |
22 | }
23 | func test_003() {
24 | let input: Int = 9
25 | let expected: String = "13211311123113112211"
26 | asyncHelper(input: input, expected: expected)
27 | }
28 | private func asyncHelper(input: Int, expected: String) {
29 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
30 | serialQueue().async(execute: { () -> Void in
31 | let result: String = Easy_038_Count_And_Say.countAndSay(input)
32 | assertHelper(expected == result, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
33 | if let unwrapped = expectation {
34 | unwrapped.fulfill()
35 | }
36 | })
37 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
38 | if error != nil {
39 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_066_Plus_One_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_066_Plus_One_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 7/16/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_066_Plus_One_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | var input: [Int] = [1, 9, 9]
14 | let expected: [Int] = [2, 0, 0]
15 | asyncHelper(input: &input, expected: expected)
16 | }
17 | func test_002() {
18 | var input: [Int] = [0]
19 | let expected: [Int] = [1]
20 | asyncHelper(input: &input, expected: expected)
21 | }
22 | func test_003() {
23 | var input: [Int] = [9]
24 | let expected: [Int] = [1, 0]
25 | asyncHelper(input: &input, expected: expected)
26 | }
27 | func test_004() {
28 | var input: [Int] = [9, 9]
29 | let expected: [Int] = [1, 0, 0]
30 | asyncHelper(input: &input, expected: expected)
31 | }
32 | private func asyncHelper(input: inout [Int], expected: [Int]) {
33 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
34 | var localInput = input
35 | serialQueue().async(execute: { () -> Void in
36 | Easy_066_Plus_One.plusOne(&localInput)
37 | let result = localInput
38 | assertHelper(result == expected, problemName:self.problemName(), input: localInput, resultValue: result, expectedValue: expected)
39 | if let unwrapped = expectation {
40 | unwrapped.fulfill()
41 | }
42 | })
43 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
44 | if error != nil {
45 | assertHelper(false, problemName:self.problemName(), input: localInput, resultValue:self.timeOutName(), expectedValue: expected)
46 | }
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_067_Add_Binary_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_067_Add_Binary_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 7/16/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_067_Add_Binary_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [String] = ["11", "1"]
14 | let expected: String = "100"
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [String] = ["10", "1"]
19 | let expected: String = "11"
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: [String] = ["10", "11"]
24 | let expected: String = "101"
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_004() {
28 | let input: [String] = ["0", "1"]
29 | let expected: String = "1"
30 | asyncHelper(input: input, expected: expected)
31 | }
32 | private func asyncHelper(input: [String], expected: String) {
33 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
34 | serialQueue().async(execute: { () -> Void in
35 | let result = Easy_067_Add_Binary.addBinary(a: input[0], b: input[1]);
36 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
37 | if let unwrapped = expectation {
38 | unwrapped.fulfill()
39 | }
40 | })
41 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
42 | if error != nil {
43 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_070_Climbing_Stairs_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_070_Climbing_Stairs_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 7/24/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_070_Climbing_Stairs_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: Int = 0
14 | let expected: Int = 1
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: Int = 1
19 | let expected: Int = 1
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: Int = 2
24 | let expected: Int = 2
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_004() {
28 | let input: Int = 3
29 | let expected: Int = 3
30 | asyncHelper(input: input, expected: expected)
31 | }
32 | func test_005() {
33 | let input: Int = 4
34 | let expected: Int = 5
35 | asyncHelper(input: input, expected: expected)
36 | }
37 | func test_006() {
38 | let input: Int = 5
39 | let expected: Int = 8
40 | asyncHelper(input: input, expected: expected)
41 | }
42 | func test_007() {
43 | let input: Int = 6
44 | let expected: Int = 13
45 | asyncHelper(input: input, expected: expected)
46 | }
47 | private func asyncHelper(input: Int, expected: Int) {
48 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
49 | serialQueue().async(execute: { () -> Void in
50 | let result = Easy_070_Climbing_Stairs.climbStairs(input)
51 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
52 | if let unwrapped = expectation {
53 | unwrapped.fulfill()
54 | }
55 | })
56 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
57 | if error != nil {
58 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Easy_088_Merge_Sorted_Array_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 10/15/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Easy_088_Merge_Sorted_Array_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | var input0: [Int] = [0]
14 | let input1: [Int] = [1]
15 | let m: Int = 0
16 | let n: Int = 1
17 | let expected: [Int] = [1]
18 | asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
19 | }
20 | func test_002() {
21 | var input0: [Int] = [1]
22 | let input1: [Int] = [0]
23 | let m: Int = 1
24 | let n: Int = 0
25 | let expected: [Int] = [1]
26 | asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
27 | }
28 | func test_003() {
29 | var input0: [Int] = [1, 3, 5, 7, 9, 0, 0, 0, 0, 0]
30 | let input1: [Int] = [2, 4, 6, 8, 10]
31 | let m: Int = 5
32 | let n: Int = 5
33 | let expected: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
34 | asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
35 | }
36 | private func asyncHelper(input0: inout [Int], input1: [Int], m: Int, n: Int, expected: [Int]) {
37 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
38 | var localInput0 = input0
39 | serialQueue().async(execute: { () -> Void in
40 | Easy_088_Merge_Sorted_Array.merge(nums1: &localInput0, m: m, nums2: input1, n: n)
41 | assertHelper(localInput0 == expected, problemName:self.problemName(), input: localInput0, resultValue: localInput0, expectedValue: expected)
42 | if let unwrapped = expectation {
43 | unwrapped.fulfill()
44 | }
45 | })
46 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
47 | if error != nil {
48 | assertHelper(false, problemName:self.problemName(), input: localInput0, resultValue:self.timeOutName(), expectedValue: expected)
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Hard/Hard_045_Jump_Game_II_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Hard_045_Jump_Game_II_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/23/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Hard_045_Jump_Game_II_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [Int] = [2, 3, 1, 1, 4]
14 | let expected: Int = 2
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [Int] = [1]
19 | let expected: Int = 0
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: [Int] = [1, 1, 1]
24 | let expected: Int = 2
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_004() {
28 | let input: [Int] = [9, 8, 1, 3, 6, 7, 7, 1,9, 8, 8, 5, 6, 7, 1]
29 | let expected: Int = 2
30 | asyncHelper(input: input, expected: expected)
31 | }
32 | func test_005() {
33 | let input: [Int] = [1, 1, 1, 3, 6, 7, 7, 1,9, 8, 8, 5, 6, 7, 1]
34 | let expected: Int = 6
35 | asyncHelper(input: input, expected: expected)
36 | }
37 | private func asyncHelper(input: [Int], expected: Int) {
38 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
39 | serialQueue().async(execute: { () -> Void in
40 | let result = Hard_045_Jump_Game_II.jump(input)
41 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
42 | if let unwrapped = expectation {
43 | unwrapped.fulfill()
44 | }
45 | })
46 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
47 | if error != nil {
48 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Hard/Hard_051_N_Queens_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Hard_051_N_Queens_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/23/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Hard_051_N_Queens_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: Int = 4
14 | let expected: [[String]] = [
15 | [
16 | ".Q..",
17 | "...Q",
18 | "Q...",
19 | "..Q."
20 | ],[
21 | "..Q.",
22 | "Q...",
23 | "...Q",
24 | ".Q.."
25 | ]
26 | ]
27 | asyncHelper(input: input, expected: expected)
28 | }
29 | private func asyncHelper(input: Int, expected: [[String]]) {
30 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
31 | serialQueue().async(execute: { () -> Void in
32 | let result = Hard_051_N_Queens.solveNQueens(input)
33 | if result.count != expected.count {
34 | assertHelper(false, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
35 | } else {
36 | for i in 0 ..< expected.count {
37 | var flag = false
38 | for j in 0 ..< result.count {
39 | if result[j] == expected[i] {
40 | flag = true
41 | }
42 | }
43 | if flag == false {
44 | assertHelper(false, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
45 | }
46 | }
47 | }
48 | if let unwrapped = expectation {
49 | unwrapped.fulfill()
50 | }
51 | })
52 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
53 | if error != nil {
54 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
55 | }
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Hard/Hard_052_N_Queens_II_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Hard_052_N_Queens_II_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/26/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Hard_052_N_Queens_II_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let expected: [Int] = [0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596, 2279184, 14772512, 95815104, 666090624]
14 | for i in 0 ..< 14 {
15 | asyncHelper(input: i, expected: expected[i])
16 | }
17 | }
18 | private func asyncHelper(input: Int, expected: Int) {
19 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
20 | serialQueue().async(execute: { () -> Void in
21 | let result = Hard_052_N_Queens_II.totalNQueens(input)
22 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
23 | if let unwrapped = expectation {
24 | unwrapped.fulfill()
25 | }
26 | })
27 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
28 | if error != nil {
29 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
30 | }
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Hard/Hard_056_Merge_Intervals_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Hard_056_Merge_Intervals_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 6/10/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Hard_056_Merge_Intervals_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [[Int]] = [
14 | [1,3],
15 | [2,6],
16 | [8,10],
17 | [15,18]
18 | ]
19 | let expected: [[Int]] = [
20 | [1,6],
21 | [8,10],
22 | [15,18]
23 | ]
24 | asyncHelper(input: input, expected: expected)
25 | }
26 | func test_002() {
27 | let input: [[Int]] = [
28 | ]
29 | let expected: [[Int]] = [
30 | ]
31 | asyncHelper(input: input, expected: expected)
32 | }
33 | func test_003() {
34 | let input: [[Int]] = [
35 | [1,3],
36 | [2,6],
37 | [8,10],
38 | [15,18],
39 | [1, 1],
40 | [11, 11],
41 | [99, 100],
42 | [98, 101],
43 | [96, 97]
44 | ]
45 | let expected: [[Int]] = [
46 | [1,6],
47 | [8,10],
48 | [11, 11],
49 | [15,18],
50 | [96, 97],
51 | [98, 101]
52 | ]
53 | asyncHelper(input: input, expected: expected)
54 | }
55 | private func asyncHelper(input: [[Int]], expected: [[Int]]) {
56 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
57 | serialQueue().async(execute: { () -> Void in
58 | let result = Hard_056_Merge_Intervals.merge(input)
59 | assertHelper(compareTwoDimensionIntArray(arr0: result, arr1: expected), problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
60 | if let unwrapped = expectation {
61 | unwrapped.fulfill()
62 | }
63 | })
64 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
65 | if error != nil {
66 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
67 | }
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_011_Container_With_Most_Water_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_011_Container_With_Most_Water.swift
3 | // Solutions
4 | //
5 | // Created by test on 3/29/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_011_Container_With_Most_Water_Test: XCTestCase, SolutionsTestCase {
12 |
13 | func test_001() {
14 | let input: [Int] = [1, 1]
15 | let expected: Int = 1
16 | let result = Medium_011_Container_With_Most_Water.maxArea(heightsArray: input)
17 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
18 | }
19 | func test_002() {
20 | let input: [Int] = [1, 2]
21 | let expected: Int = 1
22 | let result = Medium_011_Container_With_Most_Water.maxArea(heightsArray: input)
23 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
24 | }
25 | func test_003() {
26 | let input: [Int] = [1, 2, 1]
27 | let expected: Int = 2
28 | let result = Medium_011_Container_With_Most_Water.maxArea(heightsArray: input)
29 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
30 | }
31 | func test_004() {
32 | let input: [Int] = [2, 1, 2]
33 | let expected: Int = 4
34 | let result = Medium_011_Container_With_Most_Water.maxArea(heightsArray: input)
35 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
36 | }
37 | func test_005() {
38 | let input: [Int] = [2, 2, 1, 1]
39 | let expected: Int = 3
40 | let result = Medium_011_Container_With_Most_Water.maxArea(heightsArray: input)
41 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
42 | }
43 | }
44 |
45 | /*
46 | [1, 1] => 1
47 | [1, 2] => 1
48 | [1, 2, 1] => 2
49 | [2, 1, 2] => 4
50 | [2, 2, 1, 1] => 3
51 | */
52 |
53 |
54 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_012_Integer_To_Roman_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_012_Integer_To_Roman_Test.swift
3 | // Solutions
4 | //
5 | // Created by test on 3/29/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_012_Integer_To_Roman_Test: XCTestCase, SolutionsTestCase {
12 |
13 | func test_001() {
14 | let input: Int = 1
15 | let result: String = Medium_012_Integer_To_Roman.integerToRoman(num: input)
16 | let expected: String = "I"
17 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
18 | }
19 | func test_002() {
20 | let input: Int = 3999
21 | let result: String = Medium_012_Integer_To_Roman.integerToRoman(num: input)
22 | let expected: String = "MMMCMXCIX"
23 | assertHelper(result == expected, problemName: problemName(), input: input, resultValue: result, expectedValue: expected)
24 | }
25 |
26 | }
27 |
28 | /*
29 | 1 => I
30 | 3999 => MMMCMXCIX
31 | */
32 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_022_Generate_Parentheses_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_022_Generate_Parentheses_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/5/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_022_Generate_Parentheses_Test: XCTestCase, SolutionsTestCase {
12 |
13 | func test_001() {
14 | let input: Int = 1
15 | let expected: [String] = ["()"]
16 | asyncHelper(input: input, expected: expected)
17 | }
18 | func test_002() {
19 | let input: Int = 0
20 | let expected: [String] = [""]
21 | asyncHelper(input: input, expected: expected)
22 | }
23 | func test_003() {
24 | let input: Int = 3
25 | let expected: [String] = ["((()))", "(()())", "(())()", "()(())", "()()()"]
26 | asyncHelper(input: input, expected: expected)
27 | }
28 | private func asyncHelper(input: Int, expected: [String]) {
29 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
30 | serialQueue().async(execute: { () -> Void in
31 | let result: [String] = Medium_022_Generate_Parentheses.generateParenthesis(input)
32 | assertHelper(Set(expected) == Set(result), problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
33 | if let unwrapped = expectation {
34 | unwrapped.fulfill()
35 | }
36 | })
37 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
38 | if error != nil {
39 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_043_Multiply_Strings_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_043_Multiply_Strings_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/22/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_043_Multiply_Strings_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [String] = ["123", "9876"]
14 | let expected: String = "1214748"
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [String] = ["123", "00000"]
19 | let expected: String = "0"
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: [String] = ["9046720578679481304827107845738", "7307858291070163424907"]
24 | let expected: String = "66112151987897914185037067763780539471710428702996366"
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_004() {
28 | let input: [String] = ["0", "0"]
29 | let expected: String = "0"
30 | asyncHelper(input: input, expected: expected)
31 | }
32 | private func asyncHelper(input: [String], expected: String) {
33 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
34 | serialQueue().async(execute: { () -> Void in
35 | let result: String = Medium_043_Multiply_Strings.multiply(num1: input[0], num2: input[1])
36 | assertHelper(expected == result, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
37 | if let unwrapped = expectation {
38 | unwrapped.fulfill()
39 | }
40 | })
41 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
42 | if error != nil {
43 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_050_Pow_X_N_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_050_Pow_X_N_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 5/23/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_050_Pow_X_N_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [Any] = [987.654, 4]
14 | let expected: Double = pow(987.654, 4)
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [Any] = [987.654, 0]
19 | let expected: Double = pow(987.654, 0)
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: [Any] = [-987.654, 3]
24 | let expected: Double = pow(-987.654, 3)
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | private func asyncHelper(input: [Any], expected: Double) {
28 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
29 | serialQueue().async(execute: { () -> Void in
30 | let result = Medium_050_Pow_X_N.myPow(x: input[0] as! Double, n: input[1] as! Int)
31 | assertHelper(abs(expected - result) < 0.001, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
32 | if let unwrapped = expectation {
33 | unwrapped.fulfill()
34 | }
35 | })
36 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
37 | if error != nil {
38 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_059_Spiral_Matrix_II_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_059_Spiral_Matrix_II_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 6/16/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_059_Spiral_Matrix_II_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: Int = 3
14 | let expected: [[Int]] = [
15 | [ 1, 2, 3 ],
16 | [ 8, 9, 4 ],
17 | [ 7, 6, 5 ]
18 | ]
19 | asyncHelper(input: input, expected: expected)
20 | }
21 | func test_002() {
22 | let input: Int = 0
23 | let expected: [[Int]] = [
24 | ]
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_003() {
28 | let input: Int = 4
29 | let expected: [[Int]] = [
30 | [ 1, 2, 3, 4],
31 | [12,13,14, 5],
32 | [11,16,15, 6],
33 | [10, 9, 8, 7]
34 | ]
35 | asyncHelper(input: input, expected: expected)
36 | }
37 | private func asyncHelper(input: Int, expected: [[Int]]) {
38 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
39 | serialQueue().async(execute: { () -> Void in
40 | let result = Medium_059_Spiral_Matrix_II.generateMatrix(input)
41 | assertHelper(compareTwoDimensionIntArray(arr0: result, arr1: expected), problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
42 | if let unwrapped = expectation {
43 | unwrapped.fulfill()
44 | }
45 | })
46 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
47 | if error != nil {
48 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_060_Permutation_Sequence_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_060_Permutation_Sequence_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 6/17/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_060_Permutation_Sequence_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [Int] = [3, 1]
14 | let expected: String = "123"
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [Int] = [4, 24]
19 | let expected: String = "4321"
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: [Int] = [4, 23]
24 | let expected: String = "4312"
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | private func asyncHelper(input: [Int], expected: String) {
28 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
29 | serialQueue().async(execute: { () -> Void in
30 | let result = Medium_060_Permutation_Sequence.getPermutation(n: input[0], k: input[1])
31 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
32 | if let unwrapped = expectation {
33 | unwrapped.fulfill()
34 | }
35 | })
36 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
37 | if error != nil {
38 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_062_Unique_Paths_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_062_Unique_Paths_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 7/2/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_062_Unique_Paths_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [Int] = [3, 7]
14 | let expected: Int = 28
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: [Int] = [10, 20]
19 | let expected: Int = 6906900
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | private func asyncHelper(input: [Int], expected: Int) {
23 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
24 | serialQueue().async(execute: { () -> Void in
25 | let result = Medium_062_Unique_Paths.uniquePaths(m: input[0], n: input[1])
26 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
27 | if let unwrapped = expectation {
28 | unwrapped.fulfill()
29 | }
30 | })
31 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
32 | if error != nil {
33 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_069_Sqrt_X_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_069_Sqrt_X_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 7/23/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_069_Sqrt_X_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: Int = 9
14 | let expected: Int = 3
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: Int = 0
19 | let expected: Int = 0
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: Int = 5
24 | let expected: Int = 2
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | func test_004() {
28 | let input: Int = Int(sqrt(Double(Int.max)))
29 | let expected: Int = Int(sqrt(sqrt(Double(Int.max))))
30 | asyncHelper(input: input, expected: expected)
31 | }
32 | private func asyncHelper(input: Int, expected: Int) {
33 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
34 | serialQueue().async(execute: { () -> Void in
35 | let result = Medium_069_Sqrt_X.mySqrt(input)
36 | assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
37 | if let unwrapped = expectation {
38 | unwrapped.fulfill()
39 | }
40 | })
41 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
42 | if error != nil {
43 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_075_Sort_Colors_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_075_Sort_Colors_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 7/30/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_075_Sort_Colors_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | var input: [Int] = [2, 1, 1, 2, 2, 1, 0, 0, 1, 2]
14 | let expected: [Int] = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
15 | asyncHelper(input: &input, expected: expected)
16 | }
17 | private func asyncHelper(input: inout [Int], expected: [Int]) {
18 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
19 | var localInput = input
20 | serialQueue().async(execute: { () -> Void in
21 | Medium_075_Sort_Colors.sortColors(&localInput)
22 | let result = localInput
23 | assertHelper(result == expected, problemName:self.problemName(), input: localInput, resultValue: result, expectedValue: expected)
24 | if let unwrapped = expectation {
25 | unwrapped.fulfill()
26 | }
27 | })
28 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
29 | if error != nil {
30 | assertHelper(false, problemName:self.problemName(), input: localInput, resultValue:self.timeOutName(), expectedValue: expected)
31 | }
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_078_Subsets_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_078_Subsets_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 8/13/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_078_Subsets_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: [Int] = [1, 2, 3]
14 | let expected: [[Int]] = [
15 | [3],
16 | [1],
17 | [2],
18 | [1,2,3],
19 | [1,3],
20 | [2,3],
21 | [1,2],
22 | []
23 | ]
24 | asyncHelper(input: input, expected: expected)
25 | }
26 | func test_002() {
27 | let input: [Int] = []
28 | let expected: [[Int]] = [
29 | []
30 | ]
31 | asyncHelper(input: input, expected: expected)
32 | }
33 | func test_003() {
34 | let input: [Int] = [1]
35 | let expected: [[Int]] = [
36 | [],
37 | [1]
38 | ]
39 | asyncHelper(input: input, expected: expected)
40 | }
41 | func test_004() {
42 | let input: [Int] = [1, 2]
43 | let expected: [[Int]] = [
44 | [],
45 | [1],
46 | [2],
47 | [1,2]
48 | ]
49 | asyncHelper(input: input, expected: expected)
50 | }
51 | private func asyncHelper(input: [Int], expected: [[Int]]) {
52 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
53 | serialQueue().async(execute: { () -> Void in
54 | let result = Medium_078_Subsets.subsets(input)
55 | let resultSet: NSSet = NSSet(array: result)
56 | let expectedSet: NSSet = NSSet(array: expected)
57 | assertHelper(resultSet == expectedSet, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
58 | if let unwrapped = expectation {
59 | unwrapped.fulfill()
60 | }
61 | })
62 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
63 | if error != nil {
64 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
65 | }
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/Medium/Medium_096_Unique_Binary_Search_Trees_Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Medium_096_Unique_Binary_Search_Trees_Test.swift
3 | // Solutions
4 | //
5 | // Created by Di Wu on 12/8/15.
6 | // Copyright © 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class Medium_096_Unique_Binary_Search_Trees_Test: XCTestCase, SolutionsTestCase {
12 | func test_001() {
13 | let input: Int = 1
14 | let expected: Int = 1
15 | asyncHelper(input: input, expected: expected)
16 | }
17 | func test_002() {
18 | let input: Int = 3
19 | let expected: Int = 5
20 | asyncHelper(input: input, expected: expected)
21 | }
22 | func test_003() {
23 | let input: Int = 2
24 | let expected: Int = 2
25 | asyncHelper(input: input, expected: expected)
26 | }
27 | private func asyncHelper(input: Int, expected: Int) {
28 | weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
29 | serialQueue().async(execute: { () -> Void in
30 | let result_swift: Int = Medium_096_Unique_Binary_Search_Trees.numTrees(input)
31 | let result_objc: Int = ObjC_Medium_096_Unique_Binary_Search_Trees.numTrees(input)
32 | assertHelper(expected == result_swift, problemName:self.problemName(), input: input, resultValue: result_swift, expectedValue: expected)
33 | assertHelper(expected == result_objc, problemName:self.problemName(), input: input, resultValue: result_objc, expectedValue: expected)
34 | if let unwrapped = expectation {
35 | unwrapped.fulfill()
36 | }
37 | })
38 | waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
39 | if error != nil {
40 | assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Solutions/SolutionsTests/SolutionsTestsHelper.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SolutionsTestsHelper.swift
3 | // Solutions
4 | //
5 | // Created by Wu, Di on 3/30/15.
6 | // Copyright (c) 2015 diwu. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | let Default_Timeout_Value = 0.01
12 | let Default_Timeout_Suffix: String = " Time Out"
13 |
14 | protocol SolutionsTestCase {
15 | func problemName() -> String
16 | func timeOutName() -> String
17 | func timeOut() -> TimeInterval
18 | func timeOutSuffix() -> String
19 | func serialQueue() -> DispatchQueue
20 | }
21 |
22 | extension SolutionsTestCase {
23 | func problemName() -> String {
24 | return String(describing: type(of: self))
25 | }
26 | func timeOut() -> TimeInterval {
27 | return 10
28 | }
29 | func timeOutSuffix() -> String {
30 | return " Time Out"
31 | }
32 | func timeOutName() -> String {
33 | return problemName() + timeOutSuffix()
34 | }
35 | func serialQueue() -> DispatchQueue {
36 | let queue = DispatchQueue(label: problemName(), qos: .`default`, attributes: [], autoreleaseFrequency: .workItem, target: nil)
37 | return queue
38 | }
39 | }
40 |
41 | func assertHelper(_ expression: @autoclosure () -> Bool, problemName: String , input: Any, resultValue: Any, expectedValue: Any) {
42 | XCTAssert(expression(), "\n====================================\nProblem: \(problemName)\n====================================\nInput: \"\(input)\"\n====================================\nExpected: \"\(expectedValue)\"\n====================================\nResult: \"\(resultValue)\"\n====================================\n")
43 | }
44 |
45 | func compareTwoDimensionIntArray(arr0: [[Int]], arr1: [[Int]]) -> Bool {
46 | guard arr0.count == arr1.count else {
47 | return false
48 | }
49 | var count = 0
50 | for subArr0 in arr0 {
51 | let subArr1 = arr1[count]
52 | guard subArr0 == subArr1 else {
53 | return false
54 | }
55 | count += 1
56 | }
57 | return true
58 | }
59 |
60 | func convertIntArrayToNumberArr(intArr: [Int]) -> [NSNumber] {
61 | var tmpNumberArr = [NSNumber]()
62 | for i in intArr {
63 | tmpNumberArr.append(NSNumber(integerLiteral: i))
64 | }
65 | return tmpNumberArr
66 | }
67 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Easy/ObjC_Easy_100_Same_Tree.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Easy_100_Same_Tree_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Easy_100_Same_Tree_Node *left;
8 |
9 | @property (nonatomic, strong, nullable) ObjC_Easy_100_Same_Tree_Node *right;
10 |
11 | - (nonnull instancetype)initWithValue: (NSInteger) value left: (nullable ObjC_Easy_100_Same_Tree_Node *)left right: (nullable ObjC_Easy_100_Same_Tree_Node *) right NS_DESIGNATED_INITIALIZER;
12 |
13 | @end
14 |
15 | @interface ObjC_Easy_100_Same_Tree : NSObject
16 |
17 | + (BOOL)isSameTreeWithP: (nullable ObjC_Easy_100_Same_Tree_Node *)p q: (nullable ObjC_Easy_100_Same_Tree_Node *)q;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Easy/ObjC_Easy_101_Symmetric_Tree.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Easy_101_Symmetric_Tree_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Easy_101_Symmetric_Tree_Node *left;
8 |
9 | @property (nonatomic, strong, nullable) ObjC_Easy_101_Symmetric_Tree_Node *right;
10 |
11 | - (nonnull instancetype)initWithValue: (NSInteger) value left: (nullable ObjC_Easy_101_Symmetric_Tree_Node *)left right: (nullable ObjC_Easy_101_Symmetric_Tree_Node *) right NS_DESIGNATED_INITIALIZER;
12 |
13 | @end
14 |
15 | @interface ObjC_Easy_101_Symmetric_Tree : NSObject
16 |
17 | + (BOOL)isSymmetric:(nullable ObjC_Easy_101_Symmetric_Tree_Node *)root;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Hard/ObjC_Hard_004_Median_Of_Two_Sorted_Arrays.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Hard_004_Median_Of_Two_Sorted_Arrays : NSObject
4 |
5 | + (double)findMedianSortedArrays: (NSArray *)a b: (NSArray *) b;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Hard/ObjC_Hard_004_Median_Of_Two_Sorted_Arrays.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/median-of-two-sorted-arrays/
4 |
5 | #4 Median of Two Sorted Arrays
6 |
7 | Level: hard
8 |
9 | There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
10 |
11 | Inspired by @MissMary at https://leetcode.com/discuss/15790/share-my-o-log-min-m-n-solution-with-explanation
12 |
13 | */
14 |
15 | #import "ObjC_Hard_004_Median_Of_Two_Sorted_Arrays.h"
16 |
17 | @implementation ObjC_Hard_004_Median_Of_Two_Sorted_Arrays
18 |
19 | // t = O(log(min(M, N))), s = O(1)
20 | + (double)findMedianSortedArrays: (NSArray *)a b: (NSArray *) b {
21 | NSInteger m = a.count;
22 | NSInteger n = b.count;
23 | if (m > n) {
24 | return [self findMedianSortedArrays:b b:a];
25 | }
26 | NSInteger i_min = 0;
27 | NSInteger i_max = m;
28 | while (i_min <= i_max) {
29 | NSInteger i = i_min;
30 | NSInteger j = ((m + n + 1) >> 1) - i;
31 | if (j > 0 && i < m && [b[j-1] integerValue] > [a[i] integerValue]) {
32 | i_min = i + 1;
33 | } else if (i > 0 && j < n && [a[i-1] integerValue] > [b[j] integerValue]) {
34 | i_max = i - 1;
35 | } else {
36 | NSInteger num1;
37 | if (i == 0) {
38 | num1 = [b[j-1] integerValue];
39 | } else if (j == 0) {
40 | num1 = [a[i-1] integerValue];
41 | } else {
42 | num1 = MAX([a[i-1] integerValue], [b[j-1] integerValue]);
43 | }
44 | if ((m+n & 1) != 0) {
45 | return num1;
46 | }
47 | NSInteger num2;
48 | if (i >= m) {
49 | num2 = [b[j] integerValue];
50 | } else if (j >= n) {
51 | num2 = [a[i] integerValue];
52 | } else {
53 | num2 = MIN([a[i] integerValue], [b[j] integerValue]);
54 | }
55 | return ((double)num1+num2) / 2.0;
56 | }
57 | }
58 | return 0;
59 | }
60 |
61 | @end
62 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Hard/ObjC_Hard_097_Interleaving_String.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Hard_097_Interleaving_String : NSObject
4 |
5 | + (BOOL)isInterleaveWithS1: (nonnull NSString *)s1 s2: (nonnull NSString *)s2 s3: (nonnull NSString *)s3;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Hard/ObjC_Hard_097_Interleaving_String.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/interleaving-string/
4 |
5 | #97 Interleaving String
6 |
7 | Level: hard
8 |
9 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
10 |
11 | For example,
12 | Given:
13 | s1 = "aabcc",
14 | s2 = "dbbca",
15 |
16 | When s3 = "aadbbcbcac", return true.
17 | When s3 = "aadbbbaccc", return false.
18 |
19 | Inspired by @sherryxmhe at https://leetcode.com/discuss/11694/my-dp-solution-in-c
20 |
21 | */
22 |
23 | #import "ObjC_Hard_097_Interleaving_String.h"
24 |
25 | @implementation ObjC_Hard_097_Interleaving_String
26 |
27 | // t = O(N*M), s = O(N*M)
28 | + (BOOL)isInterleaveWithS1: (NSString *)s1 s2: (NSString *)s2 s3: (NSString *)s3 {
29 | if (s1.length + s2.length != s3.length) {
30 | return false;
31 | }
32 | NSMutableArray *> *dp = [NSMutableArray arrayWithCapacity:s1.length];
33 | for (NSInteger i = 0; i < s1.length + 1; i++) {
34 | dp[i] = [NSMutableArray arrayWithCapacity:s2.length];
35 | for (NSInteger j = 0; j < s2.length + 1; j++) {
36 | [dp[i] addObject:@(false)];
37 | }
38 | }
39 | for (NSInteger i = 0; i < s1.length + 1; i++) {
40 | for (NSInteger j = 0; j < s2.length + 1; j++) {
41 | if (i == 0 && j == 0) {
42 | dp[i][j] = @(true);
43 | } else if (i == 0) {
44 | dp[0][j] = @([dp[0][j-1] boolValue] && ([s2 characterAtIndex:j-1] == [s3 characterAtIndex:j-1]));
45 | } else if (j == 0) {
46 | dp[i][0] = @([dp[i-1][0] boolValue] && ([s1 characterAtIndex:i-1] == [s3 characterAtIndex:i-1]));
47 | } else {
48 | dp[i][j] = @(([dp[i][j-1] boolValue] && ([s2 characterAtIndex:j-1] == [s3 characterAtIndex:i+j-1])) || ([dp[i-1][j] boolValue] && ([s1 characterAtIndex:i-1] == [s3 characterAtIndex:i+j-1])));
49 | }
50 | }
51 | }
52 | return [dp[s1.length][s2.length] boolValue];
53 | }
54 |
55 | @end
56 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Hard/ObjC_Hard_099_Recover_Binary_Search_Tree.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Hard_099_Recover_Binary_Search_Tree_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Hard_099_Recover_Binary_Search_Tree_Node *left;
8 |
9 | @property (nonatomic, strong, nullable) ObjC_Hard_099_Recover_Binary_Search_Tree_Node *right;
10 |
11 | - (nonnull instancetype)initWithValue: (NSInteger) value left: (nullable ObjC_Hard_099_Recover_Binary_Search_Tree_Node *)left right: (nullable ObjC_Hard_099_Recover_Binary_Search_Tree_Node *) right NS_DESIGNATED_INITIALIZER;
12 |
13 | @end
14 |
15 | @interface ObjC_Hard_099_Recover_Binary_Search_Tree : NSObject
16 |
17 | + (nullable ObjC_Hard_099_Recover_Binary_Search_Tree_Node *)recoverTree: (nullable ObjC_Hard_099_Recover_Binary_Search_Tree_Node *)root;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_001_Two_Sum.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_001_Two_Sum : NSObject
4 |
5 | + (nonnull NSArray *)twoSum:(nonnull NSArray *)numbers target:(NSInteger)target;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_001_Two_Sum.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://oj.leetcode.com/problems/two-sum/
4 |
5 | #1 Two Sum
6 |
7 | Level: medium
8 |
9 | Given an array of integers, find two numbers such that they add up to a specific target number.
10 |
11 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
12 |
13 | You may assume that each input would have exactly one solution.
14 |
15 | Input: numbers={2, 7, 11, 15}, target=9
16 | Output: index1=1, index2=2
17 |
18 | Inspired by @naveed.zafar at https://leetcode.com/discuss/10947/accepted-c-o-n-solution
19 |
20 | */
21 |
22 | #import "ObjC_Medium_001_Two_Sum.h"
23 |
24 | @implementation ObjC_Medium_001_Two_Sum
25 |
26 | // t = O(N), s = O(N)
27 | + (nonnull NSArray *)twoSum:(nonnull NSArray *)numbers target:(NSInteger)target {
28 | NSMutableDictionary *hashMap = [NSMutableDictionary new];
29 | NSMutableArray *result = [NSMutableArray new];
30 | for (NSInteger i = 0; i < numbers.count; i++) {
31 | NSInteger numberToFind = target - numbers[i].integerValue;
32 | if (hashMap[@(numberToFind)] != nil) {
33 | NSInteger numberToFindIndex = hashMap[@(numberToFind)].integerValue;
34 | [result addObject:@(numberToFindIndex + 1)];
35 | [result addObject:@(i + 1)];
36 | return result;
37 | } else {
38 | hashMap[numbers[i]] = @(i);
39 | }
40 | }
41 | return result;
42 | }
43 |
44 | @end
45 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_002_Add_Two_Numbers.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_002_Add_Two_Numbers_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Medium_002_Add_Two_Numbers_Node *next;
8 |
9 | - (nonnull instancetype)init: (NSInteger) value next: (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)next NS_DESIGNATED_INITIALIZER;
10 |
11 | @end
12 |
13 | @interface ObjC_Medium_002_Add_Two_Numbers : NSObject
14 |
15 | + (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)addNumbers: (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)node1 node2: (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)node2;
16 |
17 | @end
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_002_Add_Two_Numbers.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://oj.leetcode.com/problems/add-two-numbers/
4 |
5 | #2 Add Two Numbers
6 |
7 | Level: medium
8 |
9 | You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
10 |
11 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
12 | Output: 7 -> 0 -> 8
13 |
14 | Inspired by @potpie at https://oj.leetcode.com/discuss/2308/is-this-algorithm-optimal-or-what
15 |
16 | */
17 |
18 | #import "ObjC_Medium_002_Add_Two_Numbers.h"
19 |
20 | @implementation ObjC_Medium_002_Add_Two_Numbers_Node
21 |
22 | - (instancetype)init {
23 | return [self init:0 next:nil];
24 | }
25 |
26 | - (nonnull instancetype)init: (NSInteger) value next: (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)next {
27 | if ((self = [super init])) {
28 | _value = value;
29 | _next = next;
30 | }
31 | return self;
32 | }
33 |
34 | @end
35 |
36 | @implementation ObjC_Medium_002_Add_Two_Numbers
37 |
38 | // t = O(N), s = O(1)
39 | + (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)addNumbers: (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)node1 node2: (nullable ObjC_Medium_002_Add_Two_Numbers_Node *)node2 {
40 | ObjC_Medium_002_Add_Two_Numbers_Node *tmp1 = node1;
41 | ObjC_Medium_002_Add_Two_Numbers_Node *tmp2 = node2;
42 | ObjC_Medium_002_Add_Two_Numbers_Node *dummy = [ObjC_Medium_002_Add_Two_Numbers_Node new];
43 | ObjC_Medium_002_Add_Two_Numbers_Node *curr = dummy;
44 | NSInteger sum = 0;
45 | while (tmp1 != nil || tmp2 != nil) {
46 | sum /= 10;
47 | if (tmp1 != nil) {
48 | sum += tmp1.value;
49 | tmp1 = tmp1.next;
50 | }
51 | if (tmp2 != nil) {
52 | sum += tmp2.value;
53 | tmp2 = tmp2.next;
54 | }
55 | curr.next = [[ObjC_Medium_002_Add_Two_Numbers_Node alloc] init:sum%10 next:nil];
56 | if (curr.next != nil) {
57 | curr = curr.next;
58 | }
59 | }
60 | if (sum / 10 == 1) {
61 | curr.next = [[ObjC_Medium_002_Add_Two_Numbers_Node alloc] init:1 next:nil];
62 | }
63 | return dummy.next;
64 | }
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters : NSObject
4 |
5 | + (NSInteger)longest: (nonnull NSString *)s;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
4 |
5 | #3 Longest Substring Without Repeating Characters
6 |
7 | Level: medium
8 |
9 | Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
10 |
11 | Inspired by @heiyanbin at https://oj.leetcode.com/discuss/6168/my-o-n-solution
12 |
13 | */
14 |
15 | #import "ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters.h"
16 |
17 | @implementation ObjC_Medium_003_Longest_Substring_Without_Repeating_Characters
18 |
19 | // t = O(N), s = O(1)
20 | + (NSInteger)longest: (nonnull NSString *)s {
21 | NSInteger len = s.length;
22 | if (len < 2) {
23 | return len;
24 | } else {
25 | NSInteger tmpMaxLen = 1;
26 | NSInteger maxLen = 1;
27 | NSMutableDictionary *hashMap = [NSMutableDictionary new];
28 | hashMap[@([s characterAtIndex:0])] = @(0);
29 | for (NSInteger i = 1; i < len; i++) {
30 | if (hashMap[@([s characterAtIndex:i])] != nil) {
31 | NSInteger lastPosition = [hashMap[@([s characterAtIndex:i])] integerValue];
32 | if (lastPosition + tmpMaxLen < i) {
33 | tmpMaxLen++;
34 | } else {
35 | tmpMaxLen = i - lastPosition;
36 | }
37 | } else {
38 | tmpMaxLen++;
39 | }
40 | hashMap[@([s characterAtIndex:i])] = @(i);
41 | if (tmpMaxLen > maxLen) {
42 | maxLen = tmpMaxLen;
43 | }
44 | }
45 | return maxLen;
46 | }
47 | }
48 |
49 | @end
50 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_005_Longest_Palindromic_Substring.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_005_Longest_Palindromic_Substring : NSObject
4 |
5 | + (NSString *)longestPalindrome: (NSString *)s;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_005_Longest_Palindromic_Substring.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://oj.leetcode.com/problems/longest-palindromic-substring/
4 |
5 | #5 Longest Palindromic Substring
6 |
7 | Level: medium
8 |
9 | Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
10 |
11 | Inspired by @hh1985 at https://leetcode.com/discuss/32204/simple-c-solution-8ms-13-lines
12 |
13 | */
14 |
15 | #import "ObjC_Medium_005_Longest_Palindromic_Substring.h"
16 |
17 | @implementation ObjC_Medium_005_Longest_Palindromic_Substring
18 |
19 | // t = O(N^2), s = O(1)
20 | + (nonnull NSString *)longestPalindrome: (nonnull NSString *)s {
21 | if (s.length == 0) {
22 | return @"";
23 | } else if (s.length == 1) {
24 | return s;
25 | } else {
26 | NSInteger min_start = 0;
27 | NSInteger max_len = 1;
28 | for (NSInteger i = 0; i < s.length; ) {
29 | if (s.length - i <= max_len/2) {
30 | break;
31 | }
32 | NSInteger j = i;
33 | NSInteger k = i;
34 | while (k < s.length - 1 && [s characterAtIndex:k+1] == [s characterAtIndex:k]) {
35 | k++;
36 | }
37 | i = k + 1;
38 | while (k < s.length - 1 && j > 0 && [s characterAtIndex:k+1] == [s characterAtIndex:j-1]) {
39 | k++;
40 | j--;
41 | }
42 | NSInteger new_len = k - j + 1;
43 | if (new_len > max_len) {
44 | max_len = new_len;
45 | min_start = j;
46 | }
47 | }
48 | return [s substringWithRange:NSMakeRange(min_start, max_len)];
49 | }
50 | }
51 |
52 | @end
53 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_017_Letter_Combinations_Of_A_Phone_Number.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_017_Letter_Combinations_Of_A_Phone_Number : NSObject
4 |
5 | + (nonnull NSArray *)letterCombinations: (nonnull NSString *)s;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_092_Reverse_Linked_List_II.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_092_Reverse_Linked_List_II_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Medium_092_Reverse_Linked_List_II_Node *next;
8 |
9 | - (nonnull instancetype)init: (NSInteger) value next: (nullable ObjC_Medium_092_Reverse_Linked_List_II_Node *)next NS_DESIGNATED_INITIALIZER;
10 |
11 | @end
12 |
13 | @interface ObjC_Medium_092_Reverse_Linked_List_II : NSObject
14 |
15 | + (nullable ObjC_Medium_092_Reverse_Linked_List_II_Node *)reverseBetween: (nullable ObjC_Medium_092_Reverse_Linked_List_II_Node *)head m: (NSInteger)m n: (NSInteger)n;
16 |
17 | @end
18 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_092_Reverse_Linked_List_II.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/discuss/25580/simple-java-solution-with-clear-explanation
4 |
5 | #92 Reverse Linked List II
6 |
7 | Level: medium
8 |
9 | Reverse a linked list from position m to n. Do it in-place and in one-pass.
10 |
11 | For example:
12 | Given 1->2->3->4->5->NULL, m = 2 and n = 4,
13 |
14 | return 1->4->3->2->5->NULL.
15 |
16 | Note:
17 | Given m, n satisfy the following condition:
18 | 1 ≤ m ≤ n ≤ length of list.
19 |
20 | Inspired by @ardyadipta at https://leetcode.com/discuss/25580/simple-java-solution-with-clear-explanation
21 |
22 | */
23 |
24 | #import "ObjC_Medium_092_Reverse_Linked_List_II.h"
25 |
26 | @implementation ObjC_Medium_092_Reverse_Linked_List_II_Node
27 |
28 | - (instancetype)init {
29 | return [self init:0 next:nil];
30 | }
31 |
32 | - (nonnull instancetype)init: (NSInteger) value next: (nullable ObjC_Medium_092_Reverse_Linked_List_II_Node *)next {
33 | if ((self = [super init])) {
34 | _value = value;
35 | _next = next;
36 | }
37 | return self;
38 | }
39 |
40 | @end
41 |
42 | @implementation ObjC_Medium_092_Reverse_Linked_List_II
43 |
44 | // t = O(N), s = O(1), one pass
45 | + (nullable ObjC_Medium_092_Reverse_Linked_List_II_Node *)reverseBetween: (nullable ObjC_Medium_092_Reverse_Linked_List_II_Node *)head m: (NSInteger)m n: (NSInteger)n {
46 | if (head == nil) {
47 | return nil;
48 | }
49 | ObjC_Medium_092_Reverse_Linked_List_II_Node *dummy = [ObjC_Medium_092_Reverse_Linked_List_II_Node new];
50 | dummy.next = head;
51 | ObjC_Medium_092_Reverse_Linked_List_II_Node *pre = dummy;
52 | for (NSInteger i = 0; i < m - 1; i++) {
53 | pre = pre.next;
54 | }
55 | ObjC_Medium_092_Reverse_Linked_List_II_Node *start = pre.next;
56 | ObjC_Medium_092_Reverse_Linked_List_II_Node *then = start.next;
57 | for (NSInteger i = 0; i < n - m; i++) {
58 | start.next = then.next;
59 | then.next = pre.next;
60 | pre.next = then;
61 | then = start.next;
62 | }
63 | return dummy.next;
64 | }
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_093_Restore_IP_Addresses.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_093_Restore_IP_Addresses : NSObject
4 |
5 | + (nonnull NSArray *)restoreIpAddresses: (nonnull NSString *)s;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_093_Restore_IP_Addresses.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/restore-ip-addresses/
4 |
5 | #93 Restore IP Addresses
6 |
7 | Level: medium
8 |
9 | Given a string containing only digits, restore it by returning all possible valid IP address combinations.
10 |
11 | For example:
12 | Given "25525511135",
13 |
14 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
15 |
16 | Inspired by @fiona_mao at https://leetcode.com/discuss/12790/my-code-in-java
17 |
18 | */
19 |
20 | #import "ObjC_Medium_093_Restore_IP_Addresses.h"
21 |
22 | @implementation ObjC_Medium_093_Restore_IP_Addresses
23 |
24 | // t = O(1), s = O(1)
25 | + (nonnull NSArray *)restoreIpAddresses: (nonnull NSString *)s {
26 | NSMutableArray *res = [NSMutableArray new];
27 | NSInteger len = s.length;
28 | for (NSInteger i = 1; i < 4 && i < len - 2; i++) {
29 | for (NSInteger j = i + 1; j < i + 4 && j < len - 1; j++) {
30 | for (NSInteger k = j + 1; k < j + 4 && k < len; k++) {
31 | NSString *s0 = [s substringWithRange:NSMakeRange(0, i)];
32 | NSString *s1 = [s substringWithRange:NSMakeRange(i, j-i)];
33 | NSString *s2 = [s substringWithRange:NSMakeRange(j, k-j)];
34 | NSString *s3 = [s substringWithRange:NSMakeRange(k, len-k)];
35 | if ([self p_isValid:s0] && [self p_isValid:s1] && [self p_isValid:s2] && [self p_isValid:s3]) {
36 | [res addObject:[NSString stringWithFormat:@"%@.%@.%@.%@", s0, s1, s2, s3]];
37 | }
38 | }
39 | }
40 | }
41 | return [res copy];
42 | }
43 |
44 | + (BOOL)p_isValid: (nonnull NSString *)s {
45 | if (s.length == 0) {
46 | return NO;
47 | }
48 | if (s.length > 4) {
49 | return NO;
50 | }
51 | if ([s integerValue] > 255) {
52 | return NO;
53 | }
54 | if (s.length > 1 && [s characterAtIndex:0] == '0') {
55 | return NO;
56 | }
57 | return YES;
58 | }
59 |
60 | @end
61 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_094_Binary_Tree_Inorder_Traversal.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_094_Binary_Tree_Inorder_Traversal_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Medium_094_Binary_Tree_Inorder_Traversal_Node *left;
8 |
9 | @property (nonatomic, strong, nullable) ObjC_Medium_094_Binary_Tree_Inorder_Traversal_Node *right;
10 |
11 | - (nonnull instancetype)initWithValue: (NSInteger) value left: (nullable ObjC_Medium_094_Binary_Tree_Inorder_Traversal_Node *)left right: (nullable ObjC_Medium_094_Binary_Tree_Inorder_Traversal_Node *) right NS_DESIGNATED_INITIALIZER;
12 |
13 | @end
14 |
15 | @interface ObjC_Medium_094_Binary_Tree_Inorder_Traversal : NSObject
16 |
17 | + (nonnull NSArray *)inorderTraversal: (nullable ObjC_Medium_094_Binary_Tree_Inorder_Traversal_Node *)root;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_095_Unique_Binary_Search_Trees_II.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_095_Unique_Binary_Search_Trees_II_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Medium_095_Unique_Binary_Search_Trees_II_Node *left;
8 |
9 | @property (nonatomic, strong, nullable) ObjC_Medium_095_Unique_Binary_Search_Trees_II_Node *right;
10 |
11 | - (nonnull instancetype)initWithValue: (NSInteger) value left: (nullable ObjC_Medium_095_Unique_Binary_Search_Trees_II_Node *)left right: (nullable ObjC_Medium_095_Unique_Binary_Search_Trees_II_Node *) right NS_DESIGNATED_INITIALIZER;
12 |
13 | @end
14 |
15 | @interface ObjC_Medium_095_Unique_Binary_Search_Trees_II : NSObject
16 |
17 | + (nonnull NSArray *)generateTrees:(NSInteger) n;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_096_Unique_Binary_Search_Trees.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_096_Unique_Binary_Search_Trees : NSObject
4 |
5 | + (NSInteger)numTrees: (NSInteger)n;
6 |
7 | @end
8 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_096_Unique_Binary_Search_Trees.m:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | https://leetcode.com/problems/unique-binary-search-trees/
4 |
5 | #96 Unique Binary Search Trees
6 |
7 | Level: medium
8 |
9 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
10 |
11 | For example,
12 | Given n = 3, there are a total of 5 unique BST's.
13 |
14 | 1 3 3 2 1
15 | \ / / / \ \
16 | 3 2 1 1 3 2
17 | / / \ \
18 | 2 1 2 3
19 |
20 | Inspired by @liaison at https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i
21 |
22 | */
23 |
24 | #import "ObjC_Medium_096_Unique_Binary_Search_Trees.h"
25 |
26 | @implementation ObjC_Medium_096_Unique_Binary_Search_Trees
27 |
28 | // t=O(N^2), s=O(N)
29 | + (NSInteger)numTrees: (NSInteger)n {
30 | if (n == 0 || n == 1) {
31 | return 1;
32 | }
33 | NSMutableArray *arr = [NSMutableArray arrayWithCapacity:n+1];
34 | for (NSInteger i = 0; i <= n; i++) {
35 | arr[i] = @(0);
36 | }
37 | arr[0] = @(1);
38 | arr[1] = @(1);
39 | for (NSInteger i = 2; i <= n; i++) {
40 | for (NSInteger j = 0; j < i; j++) {
41 | arr[i] = @([arr[i] integerValue] + [arr[j] integerValue] * [arr[i-1-j] integerValue]);
42 | }
43 | }
44 | return [arr[n] integerValue];
45 | }
46 |
47 | @end
48 |
--------------------------------------------------------------------------------
/Solutions/Solutions_ObjC/Medium/ObjC_Medium_098_Validate_Binary_Search_Tree.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface ObjC_Medium_098_Validate_Binary_Search_Tree_Node : NSObject
4 |
5 | @property (nonatomic, assign) NSInteger value;
6 |
7 | @property (nonatomic, strong, nullable) ObjC_Medium_098_Validate_Binary_Search_Tree_Node *left;
8 |
9 | @property (nonatomic, strong, nullable) ObjC_Medium_098_Validate_Binary_Search_Tree_Node *right;
10 |
11 | - (nonnull instancetype)initWithValue: (NSInteger) value left: (nullable ObjC_Medium_098_Validate_Binary_Search_Tree_Node *)left right: (nullable ObjC_Medium_098_Validate_Binary_Search_Tree_Node *) right NS_DESIGNATED_INITIALIZER;
12 |
13 | @end
14 |
15 | @interface ObjC_Medium_098_Validate_Binary_Search_Tree : NSObject
16 |
17 | + (BOOL)isValidBST: (nullable ObjC_Medium_098_Validate_Binary_Search_Tree_Node *)root;
18 |
19 | @end
20 |
--------------------------------------------------------------------------------