├── .gitignore
├── .travis.yml
├── InterviewInSwift.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ └── contents.xcworkspacedata
└── xcshareddata
│ └── xcschemes
│ └── InterviewInSwift.xcscheme
├── InterviewInSwift
├── AppDelegate.swift
├── Common
│ └── Extensions
│ │ ├── Character+Extensions.swift
│ │ └── String+Extensions.swift
├── Data Structure
│ └── Queue
│ │ ├── LCQueue.swift
│ │ └── LCQueueItem.swift
├── LeetCode
│ ├── LC002AddTwoNumbers.swift
│ ├── LC007ReverseInteger.swift
│ ├── LC008StringToIntegerAtoi.swift
│ ├── LC009PalindromeNumber.swift
│ ├── LC013RomanToInteger.swift
│ ├── LC014LongestCommonPrefix.swift
│ ├── LC019RemoveNthNodeFromEndOfList.swift
│ ├── LC021MergeTwoSortedLists.swift
│ ├── LC022GenerateParentheses.swift
│ ├── LC026RemoveDuplicatesFromSortedArray.swift
│ ├── LC027RemoveElement.swift
│ ├── LC028ImplementStrStr.swift
│ ├── LC046Permutations.swift
│ ├── LC047PermutationsII.swift
│ ├── LC050PowXN.swift
│ ├── LC058LengthOfLastWord.swift
│ ├── LC062UniquePaths.swift
│ ├── LC066PlusOne.swift
│ ├── LC075SortColors.swift
│ ├── LC077Combinations.swift
│ ├── LC078Subsets.swift
│ ├── LC083RemoveDuplicatesFromSortedList.swift
│ ├── LC094BinaryTreeInorderTraversal.swift
│ ├── LC098ValidateBinarySearchTree.swift
│ ├── LC100SameTree.swift
│ ├── LC102BinaryTreeLevelOrderTraversal.swift
│ ├── LC104MaximumDepthOfBinaryTree.swift
│ ├── LC110BalancedBinaryTree.swift
│ ├── LC127WordLadder.swift
│ ├── LC144BinaryTreePreorderTraversal.swift
│ ├── LC153FindMinimumInRotatedSortedArray.swift
│ ├── LC162FindPeakElement.swift
│ ├── LC205IsomorphicStrings.swift
│ ├── LC206ReverseLinkedList.swift
│ ├── LC231PowerOfTwo.swift
│ ├── LC235LowestCommonAncestorOfABinarySearchTree.swift
│ ├── LC244WordDistanceII.swift
│ ├── LC254FactorCombinations.swift
│ └── LC367ValidPerfectSquare.swift
├── Linkedin
│ ├── LKICommonAncestor.swift
│ ├── LKIIsomorphicStrings.swift
│ ├── LKIMergeTwoLists.swift
│ ├── LKIReverseLinkedList.swift
│ ├── LKISameTree.swift
│ ├── LKIShortDistance.swift
│ ├── LKIValidBST.swift
│ ├── LKIValidPerfectSquare.swift
│ └── LKIWordLadder.swift
├── LintCode
│ ├── Binary Search
│ │ ├── LCFindMinimum.swift
│ │ ├── LCFindPeakElement.swift
│ │ ├── LCFirstPosition.swift
│ │ └── LCSearch2DMatrix.swift
│ ├── Binary Tree
│ │ ├── Data Structure
│ │ │ ├── LCTreeNode.swift
│ │ │ └── LCTreeNodeHelper.swift
│ │ ├── LCBSTSearchRange.swift
│ │ ├── LCBSTValidation.swift
│ │ ├── LCBalancedTree.swift
│ │ ├── LCDepthTree.swift
│ │ ├── LCInsertTreeNode.swift
│ │ ├── LCLowestCommonAncestor.swift
│ │ ├── LCTreeInOrderTraverse.swift
│ │ ├── LCTreeLevelTraversal.swift
│ │ └── LCTreePreOrderTraverse.swift
│ ├── Integer Array
│ │ ├── LCPlusOne.swift
│ │ ├── LCRemoveDuplicates.swift
│ │ ├── LCRemoveElement.swift
│ │ ├── LCSubarraySum.swift
│ │ └── LCTwoSum.swift
│ ├── Integer
│ │ └── LCReverseInteger.swift
│ ├── Linked List
│ │ ├── Data Structure
│ │ │ ├── LCLinkedList.swift
│ │ │ └── LCLinkedListNode.swift
│ │ ├── LCAddTwoNumbers.swift
│ │ ├── LCMergeTwoLists.swift
│ │ ├── LCRemoveDuplicatesFromList.swift
│ │ ├── LCRemoveNodeFromList.swift
│ │ └── LCReverseLinkedList.swift
│ ├── Math & Bit Manipulation
│ │ ├── LCCheckPowerOf2.swift
│ │ ├── LCFlipBits.swift
│ │ └── LCUniquePaths.swift
│ ├── Search & Recursion
│ │ ├── LCPermutations.swift
│ │ ├── LCPermutationsII.swift
│ │ ├── LCSubsets.swift
│ │ └── LCWordLadder.swift
│ └── String
│ │ ├── LCAnagrams.swift
│ │ ├── LCCompareStrings.swift
│ │ └── LCStrStr.swift
└── Support Files
│ ├── Assets.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
│ └── Info.plist
├── InterviewInSwiftTests
├── Info.plist
├── LeetCode
│ ├── LC006ZigZagConversion.swift
│ ├── LC008StringToIntegerAtoiTest.swift
│ ├── LC009PalindromeNumberTest.swift
│ ├── LC013RomanToIntegerTest.swift
│ ├── LC022GenerateParenthesesTest.swift
│ ├── LC050PowXNTest.swift
│ ├── LC058LengthOfLastWordTest.swift
│ ├── LC075SortColorsTest.swift
│ ├── LC077CombinationsTest.swift
│ ├── LC100SameTreeTest.swift
│ ├── LC205IsomorphicStringsTest.swift
│ ├── LC244WordDistanceIITest.swift
│ └── LC367ValidPerfectSquareTest.swift
└── LintCode
│ ├── LCAddTwoNumbersTest.swift
│ ├── LCAnagramsTest.swift
│ ├── LCBSTSearchRangeTest.swift
│ ├── LCBSTValidationTest.swift
│ ├── LCBalancedTreeTest.swift
│ ├── LCCheckPowerOf2Test.swift
│ ├── LCCompareStringsTest.swift
│ ├── LCDepthTreeTest.swift
│ ├── LCFindMinimumTest.swift
│ ├── LCFindPeakElementTest.swift
│ ├── LCFirstPositionTest.swift
│ ├── LCFlipBitsTest.swift
│ ├── LCInsertTreeNodeTest.swift
│ ├── LCLowestCommonAncestorTest.swift
│ ├── LCMergeTwoListsTest.swift
│ ├── LCPermutationsIITest.swift
│ ├── LCPermutationsTest.swift
│ ├── LCPlusOneTest.swift
│ ├── LCRemoveDuplicatesFromListTest.swift
│ ├── LCRemoveDuplicatesTest.swift
│ ├── LCRemoveElementTest.swift
│ ├── LCRemoveNodeFromListTest.swift
│ ├── LCReverseIntegerTest.swift
│ ├── LCReverseLinkedListTest.swift
│ ├── LCSearch2DMatrixTest.swift
│ ├── LCStrStrTest.swift
│ ├── LCSubarraySumTest.swift
│ ├── LCSubsetsTest.swift
│ ├── LCTreeInOrderTraverseTest.swift
│ ├── LCTreeLevelTraversalTest.swift
│ ├── LCTreeNodeHelperTest.swift
│ ├── LCTreePreOrderTraverseTest.swift
│ ├── LCTwoSumTest.swift
│ ├── LCUniquePathsTest.swift
│ └── LCWordLadderTest.swift
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
4 |
5 | ## Build generated
6 | build/
7 | DerivedData/
8 |
9 | ## Various settings
10 | *.pbxuser
11 | !default.pbxuser
12 | *.mode1v3
13 | !default.mode1v3
14 | *.mode2v3
15 | !default.mode2v3
16 | *.perspectivev3
17 | !default.perspectivev3
18 | xcuserdata/
19 |
20 | ## Other
21 | *.moved-aside
22 | *.xcuserstate
23 |
24 | ## Obj-C/Swift specific
25 | *.hmap
26 | *.ipa
27 | *.dSYM.zip
28 | *.dSYM
29 |
30 | ## Playgrounds
31 | timeline.xctimeline
32 | playground.xcworkspace
33 |
34 | # Swift Package Manager
35 | #
36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
37 | # Packages/
38 | .build/
39 |
40 | # CocoaPods
41 | #
42 | # We recommend against adding the Pods directory to your .gitignore. However
43 | # you should judge for yourself, the pros and cons are mentioned at:
44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
45 | #
46 | # Pods/
47 |
48 | # Carthage
49 | #
50 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
51 | # Carthage/Checkouts
52 |
53 | Carthage/Build
54 |
55 | # fastlane
56 | #
57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
58 | # screenshots whenever they are needed.
59 | # For more information about the recommended setup visit:
60 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md
61 |
62 | fastlane/report.xml
63 | fastlane/Preview.html
64 | fastlane/screenshots
65 | fastlane/test_output
66 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: objective-c
2 | osx_image: xcode7.3
3 | script:
4 | - |
5 | xcodebuild test \
6 | -project InterviewInSwift.xcodeproj \
7 | -scheme InterviewInSwift \
8 | -sdk iphonesimulator \
9 | -destination 'platform=iOS Simulator,name=iPhone 6,OS=latest' | xcpretty --test
10 |
11 | after_success:
12 | - bash <(curl -s https://codecov.io/bash)
--------------------------------------------------------------------------------
/InterviewInSwift.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/InterviewInSwift.xcodeproj/xcshareddata/xcschemes/InterviewInSwift.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
31 |
32 |
34 |
40 |
41 |
42 |
43 |
44 |
50 |
51 |
52 |
53 |
54 |
55 |
65 |
67 |
73 |
74 |
75 |
76 |
77 |
80 |
81 |
82 |
88 |
90 |
96 |
97 |
98 |
99 |
101 |
102 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/InterviewInSwift/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 25/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | @UIApplicationMain
12 | class AppDelegate: UIResponder, UIApplicationDelegate {
13 |
14 | var window: UIWindow?
15 |
16 |
17 | func application(application: UIApplication,
18 | didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
19 | // Override point for customization after application launch.
20 | return true
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/InterviewInSwift/Common/Extensions/Character+Extensions.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Character+Extensions.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 19/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | extension Character {
10 | func unicodeScalarCodePoint() -> UInt32 {
11 | let characterString = String(self)
12 | let scalars = characterString.unicodeScalars
13 |
14 | return scalars[scalars.startIndex].value
15 | }
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/InterviewInSwift/Common/Extensions/String+Extensions.swift:
--------------------------------------------------------------------------------
1 | //
2 | // String+Extensions.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 15/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | extension String {
12 | func stringAtIndex(index: Int) -> String {
13 | return String(charAtIndex(index))
14 | }
15 |
16 | func unicodeAtIndex(index: Int) -> UInt32 {
17 | return charAtIndex(index).unicodeScalarCodePoint()
18 | }
19 |
20 | subscript (index: Int) -> String {
21 | let index = self.startIndex.advancedBy(index)
22 | let character = self.characters[index]
23 |
24 | return String(character)
25 | }
26 |
27 | func charAtIndex(index: Int) -> Character {
28 | let index = self.startIndex.advancedBy(index)
29 | let character = self.characters[index]
30 |
31 | return character
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/InterviewInSwift/Data Structure/Queue/LCQueue.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCQueue.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 5/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | class LCQueue {
12 | private var front: LCQueueItem
13 | private var back: LCQueueItem
14 | private var count: Int
15 |
16 | init() {
17 | back = LCQueueItem(newValue: nil)
18 | front = back
19 | count = 0
20 | }
21 |
22 | /**
23 | Add a new item to the back of the queue.
24 |
25 | - parameter value: new value
26 | */
27 | func enqueue(value: T?) {
28 | back.next = LCQueueItem(newValue: value)
29 | back = back.next!
30 | count += 1
31 | }
32 |
33 | /**
34 | Return and remove the item at the front of the queue.
35 |
36 | - returns: the front item of the queue
37 | */
38 | func dequeue() -> T? {
39 | if let newHead: LCQueueItem = front.next {
40 | front = newHead
41 | count -= 1
42 | return newHead.value
43 | }
44 |
45 | return nil
46 | }
47 |
48 | /**
49 | Return the front item
50 |
51 | - returns: front item
52 | */
53 | func peek() -> T? {
54 | return front.value
55 | }
56 |
57 | /**
58 | Return if empty for the queue
59 |
60 | - returns: true for empty otherwise false
61 | */
62 | func isEmpty() -> Bool {
63 | return front === back
64 | }
65 |
66 | /**
67 | return the size of the queue
68 |
69 | - returns: number of items
70 | */
71 | func size() -> Int {
72 | return count
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/InterviewInSwift/Data Structure/Queue/LCQueueItem.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCQueueItem.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 5/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | class LCQueueItem {
12 | let value: T?
13 | var next: LCQueueItem?
14 |
15 | init(newValue: T?) {
16 | self.value = newValue
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC002AddTwoNumbers.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC002AddTwoNumbers.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 2. Add Two Numbers
11 | https://leetcode.com/problems/add-two-numbers/
12 |
13 | 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.
14 |
15 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
16 | Output: 7 -> 0 -> 8
17 | */
18 |
19 | // LCAddTwoNumbers
20 | // Refer to LCAddTwoNumbers.swift
21 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC007ReverseInteger.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC007ReverseInteger.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 17/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 |
10 | /**
11 | 7. Reverse Integer
12 | https://leetcode.com/problems/reverse-integer/
13 |
14 | Reverse digits of an integer.
15 |
16 | Example1: x = 123, return 321
17 | Example2: x = -123, return -321
18 | */
19 | struct LC007ReverseInteger {
20 | static func reverseInteger(num: Int) -> Int {
21 | return LCReverseInteger.reverseInteger(num)
22 | }
23 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC008StringToIntegerAtoi.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC008StringToIntegerAtoi.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 19/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 8. String to Integer (atoi)
11 | https://leetcode.com/problems/string-to-integer-atoi/
12 |
13 | Implement atoi to convert a string to an integer.
14 |
15 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
16 |
17 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
18 |
19 |
20 | */
21 | struct LC008StringToIntegerAtoi {
22 | static func atoi(string: String) -> Int {
23 | var positive = true
24 | var base = 0
25 | for char in string.characters {
26 | guard char != "+" else {
27 | continue
28 | }
29 | guard char != " " else {
30 | continue
31 | }
32 | guard char != "-" else {
33 | if base == 0 {
34 | positive = false
35 | }
36 | continue
37 | }
38 | guard let intValue = Int(String(char)) else {
39 | continue
40 | }
41 | guard base < Int.max / 10 || (base == Int.max / 10 && intValue <= Int.max % 10) else {
42 | if positive {
43 | return Int.max
44 | } else {
45 | return Int.min
46 | }
47 | }
48 | base = intValue + 10 * base
49 | }
50 | if positive {
51 | return base
52 | } else {
53 | return 0 - base
54 | }
55 | }
56 | }
57 |
58 |
59 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC009PalindromeNumber.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC009PalindromeNumber.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 19/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 9. Palindrome Number
11 | https://leetcode.com/problems/palindrome-number/
12 |
13 | Determine whether an integer is a palindrome. Do this without extra space.
14 |
15 | click to show spoilers.
16 |
17 | Some hints:
18 | Could negative integers be palindromes? (ie, -1)
19 |
20 | If you are thinking of converting the integer to string, note the restriction of using extra space.
21 |
22 | 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?
23 |
24 | */
25 |
26 | struct LC009PalindromeNumber {
27 | static func isPalindrome(num: Int) -> Bool {
28 | var palindromeNum = 0
29 | var tmp = num
30 | while tmp > 0 {
31 | if palindromeNum >= Int.max / 10 {
32 | return false
33 | }
34 | palindromeNum = palindromeNum * 10 + tmp % 10
35 | tmp = tmp / 10
36 | }
37 | return palindromeNum == num
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC013RomanToInteger.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC013RomanToInteger.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 20/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 13. Roman to Integer
11 | https://leetcode.com/problems/roman-to-integer/
12 |
13 | Given a roman numeral, convert it to an integer.
14 |
15 | Input is guaranteed to be within the range from 1 to 3999.
16 | */
17 |
18 | struct LC013RomanToInteger {
19 | // O (N)
20 | // One pass
21 | static func romanToInt(s: String) -> Int {
22 | var result: Int = 0
23 | let length: Int = s.characters.count
24 | for i in (0...length-1).reverse() {
25 | let c = s[i]
26 | switch c {
27 | case "I":
28 | result += result >= 5 ? -1 : 1
29 | case "V":
30 | result += 5
31 | case "X":
32 | result += 10 * (result >= 50 ? -1 : 1)
33 | case "L":
34 | result += 50
35 | case "C":
36 | result += 100 * (result >= 500 ? -1 : 1)
37 | case "D":
38 | result += 500
39 | case "M":
40 | result += 1000
41 | default:
42 | break
43 | }
44 | }
45 | return result
46 | }
47 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC014LongestCommonPrefix.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC014LongestCommonPrefix.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 20/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC019RemoveNthNodeFromEndOfList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC019RemoveNthNodeFromEndOfList.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 19. Remove Nth Node From End of List
11 | https://leetcode.com/problems/remove-nth-node-from-end-of-list/
12 |
13 | Given a linked list, remove the nth node from the end of list and return its head.
14 |
15 | For example,
16 |
17 | Given linked list: 1->2->3->4->5, and n = 2.
18 |
19 | After removing the second node from the end, the linked list becomes 1->2->3->5.
20 | Note:
21 | Given n will always be valid.
22 | Try to do this in one pass.
23 | */
24 |
25 |
26 | // LCRemoveNodeFromList
27 | // Refer to LCRemoveNodeFromList.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC021MergeTwoSortedLists.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC021MergeTwoSortedLists.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 21. Merge Two Sorted Lists
11 | https://leetcode.com/problems/merge-two-sorted-lists/
12 |
13 | 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.
14 | */
15 |
16 |
17 |
18 | // LCMergeTwoLists
19 | // Refer to LCMergeTwoLists.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC022GenerateParentheses.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC022GenerateParentheses.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 22. Generate Parentheses
11 | https://leetcode.com/problems/generate-parentheses/
12 |
13 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
14 |
15 | For example, given n = 3, a solution set is:
16 |
17 | [
18 | "((()))",
19 | "(()())",
20 | "(())()",
21 | "()(())",
22 | "()()()"
23 | ]
24 | */
25 |
26 | class LC022GenerateParentheses {
27 | class func generateParenthesis(n: Int) -> [String] {
28 | var result: [String] = []
29 | helper(&result, str: "", n: n, m: 0)
30 | return result
31 | }
32 |
33 | class func helper(inout array: [String], str: String, n: Int, m: Int) {
34 | if m == 0 && n == 0 {
35 | array.append(str)
36 | return
37 | }
38 | if m > 0 {
39 | helper(&array, str: str + ")", n: n, m: m-1)
40 | }
41 | if n > 0 {
42 | helper(&array, str: str + "(", n: n-1, m: m+1)
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC026RemoveDuplicatesFromSortedArray.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC026RemoveDuplicatesFromSortedArray.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 26. Remove Duplicates from Sorted Array
11 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/
12 |
13 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
14 |
15 | Do not allocate extra space for another array, you must do this in place with constant memory.
16 |
17 | For example,
18 | Given input array nums = [1,1,2],
19 |
20 | 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.
21 | */
22 |
23 |
24 | // LCRemoveDuplicates
25 | // LCRemoveDuplicates.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC027RemoveElement.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC027RemoveElement.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 27. Remove Element
11 | https://leetcode.com/problems/remove-element/
12 |
13 | Given an array and a value, remove all instances of that value in place and return the new length.
14 |
15 | Do not allocate extra space for another array, you must do this in place with constant memory.
16 |
17 | The order of elements can be changed. It doesn't matter what you leave beyond the new length.
18 |
19 | Example:
20 | Given input array nums = [3,2,2,3], val = 3
21 |
22 | Your function should return length = 2, with the first two elements of nums being 2.
23 |
24 | Hint:
25 |
26 | Try two pointers.
27 | Did you use the property of "the order of elements can be changed"?
28 | What happens when the elements to remove are rare?
29 | */
30 |
31 |
32 |
33 | // LCRemoveElement
34 | // Refer to LCRemoveElement.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC028ImplementStrStr.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC028ImplementStrStr.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 28. Implement strStr()
11 | https://leetcode.com/problems/implement-strstr/
12 |
13 | Implement strStr().
14 |
15 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
16 |
17 | */
18 |
19 | // LCStrStr
20 | // Refer to LCStrStr.swift
21 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC046Permutations.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC046Permutations.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 46. Permutations
11 | https://leetcode.com/problems/permutations/
12 |
13 | Given a collection of distinct numbers, return all possible permutations.
14 |
15 | For example,
16 | [1,2,3] have the following permutations:
17 | [
18 | [1,2,3],
19 | [1,3,2],
20 | [2,1,3],
21 | [2,3,1],
22 | [3,1,2],
23 | [3,2,1]
24 | ]
25 | */
26 |
27 | // LCPermutations
28 | // Refer to LCPermutations.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC047PermutationsII.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC047PermutationsII.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 47. Permutations II
11 | https://leetcode.com/problems/permutations-ii/
12 |
13 | Given a collection of numbers that might contain duplicates, return all possible unique permutations.
14 |
15 | For example,
16 | [1,1,2] have the following unique permutations:
17 | [
18 | [1,1,2],
19 | [1,2,1],
20 | [2,1,1]
21 | ]
22 | */
23 |
24 | // LCPermutationsII
25 | // Refer to LCPermutationsII.swift
26 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC050PowXN.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC050PowXN.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 50. Pow(x, n)
11 | https://leetcode.com/problems/powx-n/
12 |
13 | Level: medium
14 |
15 | Implement pow(x, n).
16 |
17 | */
18 | struct LC050PowXN {
19 | static func myPow(x: Double, n: Int) -> Double {
20 | var x = x
21 | var n = n
22 |
23 | if n == 0 {
24 | return 1
25 | }
26 | if n < 0 {
27 | n = -n
28 | x = 1/x
29 | }
30 | return n % 2 == 0 ? myPow(x*x, n: n/2) : x * myPow(x*x, n: n/2)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC058LengthOfLastWord.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC058LengthOfLastWord.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 58. Length of Last Word
11 | https://leetcode.com/problems/length-of-last-word/
12 |
13 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
14 |
15 | If the last word does not exist, return 0.
16 |
17 | Note: A word is defined as a character sequence consists of non-space characters only.
18 |
19 | For example,
20 | Given s = "Hello World",
21 | return 5.
22 |
23 | https://discuss.leetcode.com/topic/2743/my-simple-solution-in-c/2
24 | */
25 |
26 | struct LC058LengthOfLastWord {
27 | static func lengthOfLastWord(string: String) -> Int {
28 | var length = 0
29 | var i = 0
30 | while i < string.characters.count {
31 | if string[i] != " " {
32 | length += 1
33 | } else if i + 1 < string.characters.count && string[i+1] != " " {
34 | length = 0
35 | }
36 | i += 1
37 | }
38 | return length
39 | }
40 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC062UniquePaths.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC062UniquePaths.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 62. Unique Paths
11 | https://leetcode.com/problems/unique-paths/
12 |
13 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
14 |
15 | 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).
16 |
17 | How many possible unique paths are there?
18 |
19 | Note: m and n will be at most 100.
20 | */
21 |
22 |
23 |
24 |
25 | // LCUniquePaths
26 | // Refer to LCUniquePaths
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC066PlusOne.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC066PlusOne.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 66. Plus One
11 | https://leetcode.com/problems/plus-one/
12 |
13 | Given a non-negative number represented as an array of digits, plus one to the number.
14 |
15 | The digits are stored such that the most significant digit is at the head of the list.
16 | */
17 |
18 |
19 | // LCPlusOne
20 | // Refer to LCPlusOne.swift
21 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC075SortColors.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC075SortColors.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 75. Sort Colors
11 | https://leetcode.com/problems/sort-colors/
12 |
13 | 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.
14 |
15 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
16 |
17 | Note:
18 | You are not suppose to use the library's sort function for this problem.
19 |
20 | Follow up:
21 | A rather straight forward solution is a two-pass algorithm using counting sort.
22 | 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.
23 |
24 | Could you come up with an one-pass algorithm using only constant space?
25 | */
26 |
27 | struct LC075SortColors {
28 | static func sortColors(inout nums: [Int]) {
29 | var red = -1
30 | var white = -1
31 | var blue = -1
32 | for i in 0 ..< nums.count {
33 | if nums[i] == 0 {
34 | blue += 1
35 | white += 1
36 | red += 1
37 | nums[blue] = 2
38 | nums[white] = 1
39 | nums[red] = 0
40 | } else if nums[i] == 1 {
41 | blue += 1
42 | white += 1
43 | nums[blue] = 2
44 | nums[white] = 1
45 | } else {
46 | blue += 1
47 | nums[blue] = 2
48 | }
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC077Combinations.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC077Combinations.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 22/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 77. Combinations
11 | https://leetcode.com/problems/combinations/
12 |
13 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
14 |
15 | For example,
16 | If n = 4 and k = 2, a solution is:
17 |
18 | [
19 | [2,4],
20 | [3,4],
21 | [2,3],
22 | [1,2],
23 | [1,3],
24 | [1,4],
25 | ]
26 | */
27 | struct LC077Combinations {
28 | static func combine(n: Int, k: Int) -> [[Int]] {
29 | var queue: [[Int]] = []
30 | var summary: [[Int]] = []
31 | for i in 1...n {
32 | var list: [Int] = []
33 | list.append(i)
34 | queue.append(list)
35 | }
36 | while queue.isEmpty == false {
37 | let list = queue.removeFirst()
38 | if list.count == k {
39 | summary.append(list)
40 | } else {
41 | if list.last! + 1 <= n {
42 | for i in list.last! + 1...n {
43 | var nextList: [Int] = [Int](list)
44 | nextList.append(i)
45 | queue.append(nextList)
46 | }
47 | }
48 | }
49 | }
50 | return summary
51 | }
52 | static func combineRecursionHelper(inout res: [[Int]], inout tmp: [Int], start: Int, num: Int, n: Int, k: Int) {
53 | if num == k {
54 | res.append(tmp)
55 | return
56 | }
57 | for i in start.. [[Int]] {
68 | var res: [[Int]] = []
69 | if n < k {
70 | return res
71 | }
72 | var tmp: [Int] = []
73 | combineRecursionHelper(&res, tmp: &tmp, start: 0, num: 0, n: n, k: k)
74 | return res
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC078Subsets.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC078Subsets.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 78. Subsets
11 | https://leetcode.com/problems/subsets/
12 |
13 | Given a set of distinct integers, nums, return all possible subsets.
14 |
15 | Note: The solution set must not contain duplicate subsets.
16 |
17 | For example,
18 | If nums = [1,2,3], a solution is:
19 |
20 | [
21 | [3],
22 | [1],
23 | [2],
24 | [1,2,3],
25 | [1,3],
26 | [2,3],
27 | [1,2],
28 | []
29 | ]
30 | */
31 |
32 | // LCSubsets
33 | // Refer to LCSubsets
34 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC083RemoveDuplicatesFromSortedList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC083RemoveDuplicatesFromSortedList.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 83. Remove Duplicates from Sorted List
11 | https://leetcode.com/problems/remove-duplicates-from-sorted-list/
12 |
13 | Given a sorted linked list, delete all duplicates such that each element appear only once.
14 |
15 | For example,
16 | Given 1->1->2, return 1->2.
17 | Given 1->1->2->3->3, return 1->2->3
18 | */
19 |
20 |
21 | // LCRemoveDuplicatesFromList
22 | // Refer to LCRemoveDuplicatesFromList
23 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC094BinaryTreeInorderTraversal.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC094BinaryTreeInorderTraversal.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 94. Binary Tree Inorder Traversal
11 | https://leetcode.com/problems/binary-tree-inorder-traversal/
12 |
13 | Given a binary tree, return the inorder traversal of its nodes' values.
14 |
15 | For example:
16 | Given binary tree [1,null,2,3],
17 | 1
18 | \
19 | 2
20 | /
21 | 3
22 | return [1,3,2].
23 |
24 | Note: Recursive solution is trivial, could you do it iteratively?
25 | */
26 |
27 |
28 |
29 | // Refer to LCTreeInOrderTraverse.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC098ValidateBinarySearchTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC098ValidateBinarySearchTree.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 98. Validate Binary Search Tree
11 | https://leetcode.com/problems/validate-binary-search-tree/
12 |
13 | Given a binary tree, determine if it is a valid binary search tree (BST).
14 |
15 | Assume a BST is defined as follows:
16 |
17 | The left subtree of a node contains only nodes with keys less than the node's key.
18 | The right subtree of a node contains only nodes with keys greater than the node's key.
19 | Both the left and right subtrees must also be binary search trees.
20 | Example 1:
21 | 2
22 | / \
23 | 1 3
24 | Binary tree [2,1,3], return true.
25 | Example 2:
26 | 1
27 | / \
28 | 2 3
29 | Binary tree [1,2,3], return false.
30 | */
31 | class LC098ValidateBinarySearchTree {
32 | class func isValidBST(root: LCTreeNode) -> Bool {
33 | let validation = LCBSTValidation()
34 | return validation.isValidBST(root)
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC100SameTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC100SameTree.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | /**
12 | 100. Same Tree
13 | https://leetcode.com/problems/same-tree/
14 |
15 | Given two binary trees, write a function to check if they are equal or not.
16 |
17 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
18 | */
19 | class LC100SameTree: NSObject {
20 | class func isSameTree(node1: LCTreeNode?, node2: LCTreeNode?) -> Bool {
21 | if node1 == nil && node2 == nil {
22 | return true
23 | } else if node1 == nil || node2 == nil {
24 | return false
25 | }
26 |
27 | if let node1 = node1, node2 = node2 {
28 | if node1.val == node2.val {
29 | let left = LC100SameTree.isSameTree(node1.left, node2: node2.left)
30 | let right = LC100SameTree.isSameTree(node1.right, node2: node2.right)
31 |
32 | return left && right
33 | }
34 | }
35 |
36 | return false
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC102BinaryTreeLevelOrderTraversal.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC102BinaryTreeLevelOrderTraversal.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 102. Binary Tree Level Order Traversal
11 | https://leetcode.com/problems/binary-tree-level-order-traversal/
12 |
13 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
14 |
15 | For example:
16 | Given binary tree [3,9,20,null,null,15,7],
17 | 3
18 | / \
19 | 9 20
20 | / \
21 | 15 7
22 |
23 | return its level order traversal as:
24 |
25 | [
26 | [3],
27 | [9,20],
28 | [15,7]
29 | ]
30 | */
31 |
32 |
33 |
34 | // Refer to LCTreeLevelTraversal.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC104MaximumDepthOfBinaryTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC104MaximumDepthOfBinaryTree.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 104. Maximum Depth of Binary Tree
11 | https://leetcode.com/problems/maximum-depth-of-binary-tree/
12 |
13 | Given a binary tree, find its maximum depth.
14 |
15 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
16 | */
17 |
18 |
19 |
20 | // Refer LCDepthTree.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC110BalancedBinaryTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC110BalancedBinaryTree.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 110. Balanced Binary Tree
11 | https://leetcode.com/problems/balanced-binary-tree/
12 |
13 | Given a binary tree, determine if it is height-balanced.
14 |
15 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
16 | */
17 | class LC110B {
18 | class func isBalanced(root: LCTreeNode) -> Bool {
19 | return LCBalancedTree.isBalanced(root)
20 | }
21 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC127WordLadder.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC127WordLadder.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 127. Word Ladder
11 | https://leetcode.com/problems/word-ladder/
12 |
13 | Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
14 |
15 | Only one letter can be changed at a time
16 | Each intermediate word must exist in the word list
17 | For example,
18 |
19 | Given:
20 | beginWord = "hit"
21 | endWord = "cog"
22 | wordList = ["hot","dot","dog","lot","log"]
23 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
24 | return its length 5.
25 |
26 | Note:
27 | Return 0 if there is no such transformation sequence.
28 | All words have the same length.
29 | All words contain only lowercase alphabetic characters.
30 | */
31 |
32 | // LCWordLadder
33 | // Refer to LCWordLadder.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC144BinaryTreePreorderTraversal.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC144BinaryTreePreorderTraversal.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 144. Binary Tree Preorder Traversal
11 |
12 | Given a binary tree, return the preorder traversal of its nodes' values.
13 |
14 | For example:
15 | Given binary tree {1,#,2,3},
16 | 1
17 | \
18 | 2
19 | /
20 | 3
21 | return [1,2,3].
22 |
23 | Note: Recursive solution is trivial, could you do it iteratively?
24 | */
25 |
26 |
27 | // Refer LCTreePreOrderTraverse.swift
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC153FindMinimumInRotatedSortedArray.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC153FindMinimumInRotatedSortedArray.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 153. Find Minimum in Rotated Sorted Array
11 | https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
12 |
13 | Suppose a sorted array is rotated at some pivot unknown to you beforehand.
14 |
15 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
16 |
17 | Find the minimum element.
18 |
19 | You may assume no duplicate exists in the array.
20 | */
21 | class LC153FindMinimumInRotatedSortedArray {
22 | class func findMin(nums: [Int]) -> Int {
23 | return LCFindMinimum.findMin(nums)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC162FindPeakElement.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC162FindPeakElement.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 162. Find Peak Element
11 | https://leetcode.com/problems/find-peak-element/
12 |
13 | A peak element is an element that is greater than its neighbors.
14 |
15 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
16 |
17 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
18 |
19 | You may imagine that num[-1] = num[n] = -∞.
20 |
21 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
22 |
23 | Note:
24 | Your solution should be in logarithmic complexity.
25 | */
26 | class LC162FindPeakElement {
27 | class func findPeak(nums: [Int]) -> Int {
28 | return LCFindPeakElement.findPeak(nums)
29 | }
30 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC205IsomorphicStrings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC205IsomorphicStrings.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // 205. Isomorphic Strings
12 | // https://leetcode.com/problems/isomorphic-strings/
13 |
14 | /**
15 | Given two strings s and t, determine if they are isomorphic.
16 |
17 | Two strings are isomorphic if the characters in s can be replaced to get t.
18 |
19 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
20 |
21 | For example,
22 | Given "egg", "add", return true.
23 |
24 | Given "foo", "bar", return false.
25 |
26 | Given "paper", "title", return true.
27 | */
28 | class LC205IsomorphicStrings: NSObject {
29 | class func isIsomorphic(source: String, target: String) -> Bool {
30 | var map = [String : String]()
31 |
32 | if source.characters.count != target.characters.count {
33 | return false
34 | }
35 |
36 | for i in 0 ..< source.characters.count {
37 | if let mappingCharacter = map[source.stringAtIndex(i)] {
38 | if mappingCharacter != target.stringAtIndex(i) {
39 | return false
40 | }
41 | } else {
42 | map[source.stringAtIndex(i)] = target.stringAtIndex(i)
43 | }
44 | }
45 |
46 | return true
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC206ReverseLinkedList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC206ReverseLinkedList.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 206. Reverse Linked List
11 | https://leetcode.com/problems/reverse-linked-list/
12 |
13 | Reverse a singly linked list.
14 |
15 | Hint:
16 | A linked list can be reversed either iteratively or recursively. Could you implement both?
17 | */
18 |
19 | // LCReverseLinkedList
20 | // Refer to LCReverseLinkedList
21 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC231PowerOfTwo.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC231PowerOfTwo.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 231. Power of Two
11 | https://leetcode.com/problems/power-of-two/
12 |
13 | Given an integer, write a function to determine if it is a power of two.
14 | */
15 |
16 |
17 | // LCCheckPowerOf2
18 | // Refer to LCCheckPowerOf2.swift
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC235LowestCommonAncestorOfABinarySearchTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC235LowestCommonAncestorOfABinarySearchTree.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 235. Lowest Common Ancestor of a Binary Search Tree
11 | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
12 |
13 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
14 |
15 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
16 |
17 | _______6______
18 | / \
19 | ___2__ ___8__
20 | / \ / \
21 | 0 _4 7 9
22 | / \
23 | 3 5
24 | For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
25 | */
26 |
27 |
28 | // LCLowestCommonAncestor
29 | // Refer to LCLowestCommonAncestor.swift
30 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC244WordDistanceII.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC244WordDistanceII.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Shortest Word Distance II
12 | // https://leetcode.com/problems/shortest-word-distance-ii/
13 |
14 | /**
15 | Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list.
16 |
17 | For example,
18 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
19 |
20 | Given word1 = “coding”, word2 = “practice”, return 3.
21 | Given word1 = "makes", word2 = "coding", return 1.
22 |
23 | Note:
24 | You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
25 | */
26 |
27 | class LC244WordDistanceII: NSObject {
28 |
29 | var map: [String: [Int]]
30 |
31 | init(words: [String]) {
32 | map = [String: [Int]]()
33 | for i in 0 ..< words.count {
34 | let word = words[i]
35 | if map[word] != nil {
36 | map[word]?.append(i)
37 | } else {
38 | var list: [Int] = []
39 | list.append(i)
40 | map[word] = list
41 | }
42 | }
43 | }
44 |
45 | func shortest(word1: String, word2: String) -> Int {
46 | let index1 = map[word1]!
47 | let index2 = map[word2]!
48 |
49 | var distance = Int.max
50 |
51 | for i in index1 {
52 | for j in index2 {
53 | distance = min(distance, abs(i-j))
54 | }
55 | }
56 |
57 | return distance
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC254FactorCombinations.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC254FactorCombinations.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 15/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // 254 Factor Combinations
12 | // https://leetcode.com/problems/factor-combinations/
13 |
14 | /**
15 | Numbers can be regarded as product of its factors. For example,
16 |
17 | 1
18 | 2
19 | 8 = 2 x 2 x 2;
20 | = 2 x 4.
21 | Write a function that takes an integer n and return all possible combinations of its factors.
22 |
23 | Note:
24 |
25 | Each combination’s factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
26 |
27 | You may assume that n is always positive.
28 |
29 | Factors should be greater than 1 and less than n.
30 |
31 | Examples:
32 |
33 | input: 1
34 |
35 | output:
36 | []
37 | input: 37
38 |
39 | output:
40 | []
41 | input: 12
42 |
43 | output:
44 | [
45 | [2, 6],
46 | [2, 2, 3],
47 | [3, 4]
48 | ]
49 | input: 32
50 |
51 | output:
52 | [
53 | [2, 16],
54 | [2, 2, 8],
55 | [2, 2, 2, 4],
56 | [2, 2, 2, 2, 2],
57 | [2, 4, 4],
58 | [4, 8]
59 | ]
60 | */
61 | class LC254FactorCombinations: NSObject {
62 | // func allFactors(num: Int) -> [[Int]] {
63 | // var result = Set<[Int]>()
64 |
65 |
66 |
67 | // }
68 | //
69 | //
70 | // Set> result = new HashSet<>();
71 | //
72 | // int dist = (int) Math.sqrt(n);
73 | //
74 | // for (int i = 2; i <= dist; i++) {
75 | // if (n % i == 0) {
76 | // List> tmp = helper(n / i);
77 | // for (List l : tmp) {
78 | // l.add(i);
79 | // Collections.sort(l);
80 | // result.add(l);
81 | // }
82 | // }
83 | // }
84 | // return new ArrayList<>(result);
85 | // }
86 | //
87 | // public List> helper(int n) {
88 | // List> result = new ArrayList<>();
89 | //
90 | // List t = new ArrayList<>();
91 | // t.add(n);
92 | // result.add(t);
93 | //
94 | // int dist = (int) Math.sqrt(n);
95 | //
96 | // for (int i = 2; i <= dist; i++) {
97 | // if (n % i == 0) {
98 | // List> tmp = helper(n / i);
99 | // for (List l : tmp) {
100 | // l.add(i);
101 | // result.add(l);
102 | // }
103 | // }
104 | // }
105 | // return result;
106 | // }
107 | }
108 |
--------------------------------------------------------------------------------
/InterviewInSwift/LeetCode/LC367ValidPerfectSquare.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC367ValidPerfectSquare.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Valid Perfect Square
12 | // https://leetcode.com/problems/valid-perfect-square/
13 | class LC367ValidPerfectSquare: NSObject {
14 | class func isPerfectSquare(num: Int) -> Bool {
15 | var start = 1
16 | var end = num >> 1 + 1
17 |
18 | while start <= end {
19 | let middle = start + (end - start) >> 1
20 | let square = middle * middle
21 |
22 | if square == num {
23 | return true
24 | } else if square > num {
25 | end = middle - 1
26 | } else {
27 | start = middle + 1
28 | }
29 | }
30 |
31 | return false
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKICommonAncestor.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKICommonAncestor.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | /// Refer to `LCLowestCommonAncestor`
12 |
13 | // Find common ancestor in binary tree
14 | class LKICommonAncestor: NSObject {
15 | class func lowestCommonAncestor(root: LCTreeNode?,
16 | node1: LCTreeNode,
17 | node2: LCTreeNode) -> LCTreeNode? {
18 | return LCLowestCommonAncestor.lowestCommonAncestor(root, node1: node1, node2: node2)
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIIsomorphicStrings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIIsomorphicStrings.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 15/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Refer to `LC205IsomorphicStrings`
12 | // Given two words as Strings, determine if they are isomorphic. Two words are called isomorphic if the letters in one word can be remapped to get the second word. Remapping a letter means replacing all occurrences of it with another letter while the ordering of the letters remains unchanged. No two letters may map to the same letter, but a letter may map to itself.
13 |
14 | class LKIIsomorphicStrings: NSObject {
15 | class func isIsomorphic(source: String, target: String) -> Bool {
16 | return LC205IsomorphicStrings.isIsomorphic(source, target: target)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIMergeTwoLists.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIMergeTwoLists.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 13/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Refer to `LCMergeTwoLists`
12 | // Merge two sorted lists
13 |
14 | class LKIMergeTwoLists: NSObject {
15 | class func mergeTwoLists(l1: LCLinkedListNode, l2: LCLinkedListNode) -> LCLinkedListNode {
16 | return LCMergeTwoLists.mergeTwoLists(l1, l2: l2)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIReverseLinkedList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIReverseLinkedList.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | /// Reverse a linked list
12 |
13 | // Refer to `LCReverseLinkedList`
14 | class LKIReverseLinkedList: NSObject {
15 | class func reverse(head: LCLinkedListNode) -> LCLinkedListNode {
16 | return LCReverseLinkedList.reverse(head)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKISameTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKISameTree.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Refer to `LC100SameTree`
12 | // Same tree, mirror tree
13 | class LKISameTree: NSObject {
14 | class func isSameTree(node1: LCTreeNode?, node2: LCTreeNode?) -> Bool {
15 | return LC100SameTree.isSameTree(node1, node2: node2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIShortDistance.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIShortDistance.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Refer to `LC244WordDistanceII`
12 | // Find the minimum distance between 2 words in a dictionary
13 |
14 | class LKIShortDistance: NSObject {
15 | class func shortDistance(words: [String], word1: String, word2: String) -> Int {
16 | let distance = LC244WordDistanceII.init(words: words)
17 | return distance.shortest(word1, word2: word2)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIValidBST.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIValidBST.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | /// refer to `LCBSTValidation`
12 |
13 | // validate is a binary search tree is legit
14 | class LKIValidBST: NSObject {
15 | class func isValidBST(root: LCTreeNode?) -> Bool {
16 | let validator = LCBSTValidation()
17 | return validator.isValidBST(root)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIValidPerfectSquare.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIValidPerfectSquare.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Refer `LC367ValidPerfectSquare`
12 | // Determine whether a number has an integer square root
13 |
14 | class LKIValidPerfectSquare: NSObject {
15 | class func isPerfectSquare(num: Int) -> Bool {
16 | return LC367ValidPerfectSquare.isPerfectSquare(num)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/Linkedin/LKIWordLadder.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LKIWordLadder.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Refer to Word Ladder
12 | // Given a dictionary find and set of two words find path from one word to another such that all the intermediate words are also from dictionary.
13 | // Example: GOD -> GID -> DID -> DIG -> DOG.
14 | // At each time we are allowed only one character change.
15 | class LKIWordLadder: NSObject {
16 |
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Search/LCFindMinimum.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFindMinimum.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Find Minimum in Rotated Sorted Array
10 | // http://www.lintcode.com/en/problem/find-minimum-in-rotated-sorted-array/
11 | class LCFindMinimum {
12 | /**
13 | the minimum number in the array
14 |
15 | - parameter nums: a rotated sorted array
16 |
17 | - returns: the minimum number in the array
18 | */
19 | class func findMin(nums: [Int]) -> Int {
20 | if nums.count == 0 {
21 | return -1
22 | }
23 |
24 | var start = 0, end = nums.count - 1
25 | let target = nums[nums.count - 1]
26 |
27 | // find the first element <= target
28 | while start + 1 < end {
29 | let mid = start + (end - start) / 2
30 | if nums[mid] <= target {
31 | end = mid
32 | } else {
33 | start = mid
34 | }
35 | }
36 |
37 | if nums[start] <= target {
38 | return nums[start]
39 | } else {
40 | return nums[end]
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Search/LCFindPeakElement.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFindPeakElement.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Find Peak Element
10 | // http://www.lintcode.com/en/problem/find-peak-element/
11 | class LCFindPeakElement {
12 | /**
13 | * @param nums: An integers array.
14 | * @return: return any of peek positions.
15 | */
16 | class func findPeak(nums: [Int]) -> Int {
17 | let n = nums.count
18 | if n == 1 {
19 | return 0
20 | }
21 |
22 | var start = 0
23 | var end = n - 1
24 | var mid = 0
25 |
26 | while start <= end {
27 | mid = start + (end - start) / 2
28 | if (mid == 0 || nums[mid] >= nums[mid - 1]) && (mid == n - 1 || nums[mid] >= nums[mid + 1]) {
29 | return mid
30 | } else if mid > 0 && nums[mid-1] > nums[mid] {
31 | end = mid - 1
32 | } else {
33 | start = mid + 1
34 | }
35 | }
36 |
37 | return mid
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Search/LCFirstPosition.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFirstPosition.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | First Position of Target
11 | http://www.lintcode.com/en/problem/first-position-of-target/
12 |
13 | For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.
14 |
15 | If the target number does not exist in the array, return -1.
16 | */
17 | class LCFirstPosition {
18 | /**
19 | * @param nums: The integer array.
20 | * @param target: Target to find.
21 | * @return: The first position of target. Position starts from 0.
22 | */
23 | class func binarySearch(nums: [Int], target: Int) -> Int {
24 | if nums.count == 0 {
25 | return -1
26 | }
27 |
28 | var start = 0
29 | var end = nums.count - 1
30 |
31 | while start + 1 < end {
32 | let mid = start + (end - start) / 2
33 | if nums[mid] == target {
34 | end = mid
35 | } else if nums[mid] < target {
36 | start = mid
37 | } else {
38 | end = mid
39 | }
40 | }
41 |
42 | if nums[start] == target {
43 | return start
44 | }
45 |
46 | if nums[end] == target {
47 | return end
48 | }
49 |
50 | return -1
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Search/LCSearch2DMatrix.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCSearch2DMatrix.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Search a 2D Matrix
12 | //http://www.lintcode.com/en/problem/search-a-2d-matrix/
13 | class LCSearch2DMatrix: NSObject {
14 | /**
15 | * @param matrix, a list of lists of integers
16 | * @param target, an integer
17 | * @return a boolean, indicate whether matrix contains target
18 | */
19 | class func searchMatrix(matrix: [[Int]], target: Int) -> Bool {
20 | if (matrix.count == 0) {
21 | return false
22 | }
23 |
24 | if (matrix[0].count == 0) {
25 | return false
26 | }
27 |
28 | // from bottom left to top right
29 | let n = matrix.count
30 | let m = matrix[0].count
31 | var x = n - 1
32 | var y = 0
33 | var count = 0
34 |
35 | while x >= 0 && y < m {
36 | if matrix[x][y] < target {
37 | y += 1
38 | } else if matrix[x][y] > target {
39 | x -= 1
40 | } else {
41 | count += 1
42 | x -= 1
43 | y += 1
44 | }
45 | }
46 |
47 | return count > 0
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/Data Structure/LCTreeNode.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeNode.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | class LCTreeNode: NSObject {
12 | var val: Int
13 | var left: LCTreeNode?
14 | var right: LCTreeNode?
15 |
16 | init(val: Int) {
17 | self.val = val
18 | }
19 |
20 | init(val: Int, left: LCTreeNode?, right: LCTreeNode?) {
21 | self.val = val
22 | self.left = left
23 | self.right = right
24 | }
25 |
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/Data Structure/LCTreeNodeHelper.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeNodeHelper.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | class LCTreeNodeHelper: NSObject {
12 | /**
13 | Compare two `LCTreeNode` nodes
14 |
15 | - parameter node1: `LCTreeNode` node
16 | - parameter node2: `LCTreeNode` node
17 |
18 | - returns: true if two nodes are the same, otherwise return false
19 | */
20 | class func compare(node1: LCTreeNode?, node2: LCTreeNode?) -> Bool {
21 | if let currentNode1 = node1, currentNode2 = node2 {
22 | if currentNode1.val != currentNode2.val {
23 | return false
24 | } else {
25 | var isSame = false
26 | isSame = compare(currentNode1.left, node2: currentNode2.left)
27 | isSame = compare(currentNode1.right, node2: currentNode2.right)
28 | return isSame
29 | }
30 |
31 | } else if node1 == nil && node2 == nil {
32 | return true
33 | }
34 |
35 | return false
36 | }
37 |
38 | /**
39 | Create `LCTreeNode` by passing string
40 |
41 | For example,
42 | 3,9,20,#,#,15,7
43 |
44 | will generate the tree below
45 |
46 | 3
47 | / \
48 | 9 20
49 | / \
50 | 15 7
51 |
52 | - parameter nodesString: all nodes value from top to bottom,
53 | '#' from empty node, use ',' to separate
54 |
55 | - returns: `LCTreeNode` object
56 | */
57 | class func createTreeNode(nodesString: String) -> LCTreeNode {
58 | let nodes = nodesString.componentsSeparatedByString(",")
59 |
60 | var queue: [LCTreeNode] = []
61 | let root = LCTreeNode.init(val: Int(nodes[0])!)
62 | queue.append(root)
63 |
64 | var index = 0
65 | var isLeftChild = true
66 |
67 | for i in 1.. LCTreeNode? {
90 | if root.val == value {
91 | return root
92 | }
93 |
94 | if root.left != nil {
95 | if let left = LCTreeNodeHelper.treeNode(root.left!, value: value) {
96 | return left
97 | }
98 | }
99 |
100 | if root.right != nil {
101 | if let right = LCTreeNodeHelper.treeNode(root.right!, value: value) {
102 | return right
103 | }
104 | }
105 |
106 | return nil
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCBSTSearchRange.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCBSTSearchRange.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 6/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | // Search Range in Binary Search Tree
12 | // http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/
13 | class LCBSTSearchRange: NSObject {
14 | private var result: [Int]!
15 |
16 | /**
17 | * @param root: The root of the binary search tree.
18 | * @param k1 and k2: range k1 to k2.
19 | * @return: Return all keys that k1<=key<=k2 in increasing order.
20 | */
21 | func searchRange(root: LCTreeNode, k1: Int, k2: Int) -> [Int] {
22 | result = []
23 | helper(root, k1: k1, k2: k2)
24 | return result
25 | }
26 |
27 | private func helper(root: LCTreeNode?, k1: Int, k2: Int) {
28 | if let node = root {
29 | if node.val > k1 {
30 | helper(node.left, k1: k1, k2: k2)
31 | }
32 |
33 | if node.val >= k1 && node.val <= k2 {
34 | result.append(node.val)
35 | }
36 |
37 | if node.val < k2 {
38 | helper(node.right, k1: k1, k2: k2)
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCBSTValidation.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCBSTValidation.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 4/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 |
10 | // Validate Binary Search Tree
11 | // http://www.lintcode.com/en/problem/validate-binary-search-tree/
12 |
13 | class LCBSTValidation {
14 | private var lastVal = Int.min
15 | private var firstNode = true
16 |
17 | func isValidBST(root: LCTreeNode?) -> Bool {
18 | if let node = root {
19 | if !isValidBST(node.left) {
20 | return false
21 | }
22 |
23 | if !firstNode && lastVal >= node.val {
24 | return false
25 | }
26 |
27 | firstNode = false
28 | lastVal = node.val
29 | if (!isValidBST(node.right)) {
30 | return false
31 | }
32 | }
33 |
34 | return true
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCBalancedTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCBalancedTree.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 30/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Balanced Binary Tree
10 | // http://www.lintcode.com/en/problem/balanced-binary-tree/
11 |
12 | class LCBalancedTree {
13 | /**
14 | * @param root: The root of binary tree.
15 | * @return: True if this Binary tree is Balanced, or false.
16 | */
17 | class func isBalanced(root: LCTreeNode) -> Bool {
18 | return LCBalancedTree.maxDepth(root) != -1
19 | }
20 |
21 | private class func maxDepth(root: LCTreeNode?) -> Int {
22 | if let node = root {
23 | let left = LCDepthTree.maxDepth(node.left)
24 | let right = LCDepthTree.maxDepth(node.right)
25 |
26 | if (left == -1 || right == -1 || abs(left - right) > 1) {
27 | return -1
28 | }
29 |
30 | return max(left, right) + 1
31 | } else {
32 | return 0
33 | }
34 |
35 |
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCDepthTree.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCDepthTree.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Maximum Depth of Binary Tree
12 | // http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/
13 | class LCDepthTree: NSObject {
14 | var depth: Int
15 |
16 | override init() {
17 | depth = 0
18 | }
19 |
20 | func helper(node: LCTreeNode?, curtDepth: Int) {
21 | if let currentNode = node {
22 | if curtDepth > depth {
23 | depth = curtDepth
24 | }
25 |
26 | helper(currentNode.left, curtDepth: curtDepth + 1)
27 | helper(currentNode.right, curtDepth: curtDepth + 1)
28 | }
29 | }
30 |
31 | func maxDepthByTraverse(root: LCTreeNode) -> Int {
32 | depth = 0
33 | helper(root, curtDepth: 1)
34 |
35 | return depth
36 | }
37 | }
38 |
39 | extension LCDepthTree {
40 | class func maxDepth(root: LCTreeNode?) -> Int {
41 | guard let root = root else {
42 | return 0
43 | }
44 |
45 | let left = LCDepthTree.maxDepth(root.left)
46 | let right = LCDepthTree.maxDepth(root.right)
47 |
48 | return max(left, right) + 1
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCInsertTreeNode.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCInsertTreeNode.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 30/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Insert Node in a Binary Search Tree
10 | // http://www.lintcode.com/en/problem/insert-node-in-a-binary-search-tree/
11 |
12 | class LCInsertTreeNode {
13 | /**
14 | * @param root: The root of the binary search tree.
15 | * @param node: insert this node into the binary search tree
16 | * @return: The root of the new binary search tree.
17 | */
18 | class func insertNode(root: LCTreeNode?, node: LCTreeNode) -> LCTreeNode? {
19 | if let currentNode = root {
20 | if currentNode.val > node.val {
21 | currentNode.left = LCInsertTreeNode.insertNode(currentNode.left, node: node)
22 | } else {
23 | currentNode.right = LCInsertTreeNode.insertNode(currentNode.right, node: node)
24 | }
25 | return currentNode
26 | } else {
27 | return nil
28 | }
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCLowestCommonAncestor.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCLowestCommonAncestor.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Lowest Common Ancestor
10 | // http://www.lintcode.com/en/problem/lowest-common-ancestor/
11 | class LCLowestCommonAncestor {
12 | /**
13 | * @param root: The root of the binary search tree.
14 | * @param A and B: two nodes in a Binary.
15 | * @return: Return the least common ancestor(LCA) of the two nodes.
16 | */
17 | class func lowestCommonAncestor(root: LCTreeNode?, node1: LCTreeNode, node2: LCTreeNode) -> LCTreeNode? {
18 | guard let root = root else {
19 | return nil
20 | }
21 |
22 | if root == node1 || root == node2 {
23 | return root
24 | }
25 |
26 | // Divide
27 | let left = LCLowestCommonAncestor.lowestCommonAncestor(root.left, node1: node1, node2: node2)
28 | let right = LCLowestCommonAncestor.lowestCommonAncestor(root.right, node1: node1, node2: node2)
29 |
30 | // Conquer
31 | if left != nil && right != nil {
32 | return root
33 | }
34 |
35 | if left != nil {
36 | return left
37 | }
38 |
39 | if right != nil {
40 | return right
41 | }
42 |
43 | return nil
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCTreeInOrderTraverse.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeInOrderTraverse.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 10/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Binary Tree Inorder Traversal
10 | // http://www.lintcode.com/en/problem/binary-tree-inorder-traversal/
11 | class LCTreeInOrderTraverse {
12 | class func enumerateTreeNode(node: LCTreeNode?, result: Int -> Void) {
13 | if let current = node {
14 | enumerateTreeNode(current.left, result: result)
15 | result(current.val)
16 | enumerateTreeNode(current.right, result: result)
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCTreeLevelTraversal.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeLevelTraversal.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 5/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Binary Tree Level Order Traversal
12 | // http://www.lintcode.com/en/problem/binary-tree-level-order-traversal/
13 |
14 | enum TraversalType {
15 | case BFS
16 | case DFS
17 | case BFSWithTwoQueues
18 | case BFSQueueWithDummyNode
19 | }
20 |
21 | class LCTreeLevelTraversal: NSObject {
22 | static let ErrorState = [[-1]]
23 |
24 | class func levelOrder(root: LCTreeNode, methods: TraversalType) -> [[Int]] {
25 | switch methods {
26 | case TraversalType.BFS:
27 | return LCTreeLevelTraversal.levelOrderByBFS(root)
28 | case TraversalType.DFS:
29 | let treeLevelTraversal = LCTreeLevelTraversal()
30 | return treeLevelTraversal.levelOrderByDFS(root)
31 | case TraversalType.BFSWithTwoQueues:
32 | return LCTreeLevelTraversal.levelOrderByBFSWithTwoQueues(root)
33 | case TraversalType.BFSQueueWithDummyNode:
34 | return LCTreeLevelTraversal.levelOrderByBFSQueueWithDummyNode(root)
35 | }
36 | }
37 |
38 | }
39 |
40 | // BFS solution
41 | extension LCTreeLevelTraversal {
42 | class func levelOrderByBFS(root: LCTreeNode?) -> [[Int]] {
43 | var result = [[Int]]()
44 |
45 | guard let node = root else {
46 | return LCTreeLevelTraversal.ErrorState
47 | }
48 |
49 | let queue = LCQueue()
50 | queue.enqueue(node)
51 |
52 | while !queue.isEmpty() {
53 | var level: [Int] = []
54 | let size = queue.size()
55 | for _ in 0 ..< size {
56 |
57 | guard let head = queue.dequeue() else {
58 | preconditionFailure("Head is required")
59 | }
60 |
61 | level.append(head.val)
62 |
63 | if let left = head.left {
64 | queue.enqueue(left)
65 | }
66 |
67 | if let right = head.right {
68 | queue.enqueue(right)
69 | }
70 | }
71 | result.append(level)
72 | }
73 | return result
74 | }
75 | }
76 |
77 | // DFS solution
78 | extension LCTreeLevelTraversal {
79 | func levelOrderByDFS(root: LCTreeNode?) -> [[Int]] {
80 | var results = [[Int]]()
81 |
82 | guard let node = root else {
83 | return LCTreeLevelTraversal.ErrorState
84 | }
85 |
86 | var maxLevel = 0
87 | while true {
88 | var level: [Int] = []
89 | dfs(node, level: &level, curtLevel: 0, maxLevel: maxLevel)
90 | if level.count == 0 {
91 | break
92 | }
93 |
94 | results.append(level)
95 | maxLevel += 1
96 | }
97 |
98 | return results
99 | }
100 |
101 | private func dfs(root: LCTreeNode?, inout level: [Int], curtLevel: Int, maxLevel: Int) {
102 | if curtLevel > maxLevel {
103 | return
104 | }
105 |
106 | guard let node = root else {
107 | return
108 | }
109 |
110 | if curtLevel == maxLevel {
111 | level.append(node.val)
112 | return
113 | }
114 |
115 | dfs(node.left, level: &level, curtLevel: curtLevel + 1, maxLevel: maxLevel)
116 | dfs(node.right, level: &level, curtLevel: curtLevel + 1, maxLevel: maxLevel)
117 |
118 | }
119 | }
120 |
121 | // BFS with two queues
122 | extension LCTreeLevelTraversal {
123 | class func levelOrderByBFSWithTwoQueues(root: LCTreeNode?) -> [[Int]] {
124 | var results = [[Int]]()
125 |
126 | guard let node = root else {
127 | return LCTreeLevelTraversal.ErrorState
128 | }
129 |
130 | var q1: [LCTreeNode] = []
131 | var q2: [LCTreeNode] = []
132 |
133 | q1.append(node)
134 |
135 | while q1.count != 0 {
136 | var level: [Int] = []
137 | q2.removeAll()
138 |
139 | for currentNode in q1 {
140 | level.append(currentNode.val)
141 |
142 | if let left = currentNode.left {
143 | q2.append(left)
144 | }
145 |
146 | if let right = currentNode.right {
147 | q2.append(right)
148 | }
149 | }
150 |
151 | // swap q1 and q2
152 | let temp = q1
153 | q1 = q2
154 | q2 = temp
155 |
156 | // add to result
157 | results.append(level)
158 | }
159 | return results
160 | }
161 | }
162 |
163 | // BFS, queue with dummy node
164 | extension LCTreeLevelTraversal {
165 | class func levelOrderByBFSQueueWithDummyNode(root: LCTreeNode?) -> [[Int]] {
166 | var results = [[Int]]()
167 |
168 | guard let node = root else {
169 | return LCTreeLevelTraversal.ErrorState
170 | }
171 |
172 | let queue = LCQueue()
173 | queue.enqueue(node)
174 | queue.enqueue(nil) // dummy node
175 |
176 | var level: [Int] = []
177 | while !queue.isEmpty() {
178 | if let currentNode = queue.dequeue() {
179 | level.append(currentNode.val)
180 |
181 | if let left = currentNode.left {
182 | queue.enqueue(left)
183 | }
184 |
185 | if let right = currentNode.right {
186 | queue.enqueue(right)
187 | }
188 |
189 | } else {
190 | if level.count == 0 {
191 | break
192 | }
193 |
194 | results.append(level)
195 | level = []
196 | queue.enqueue(nil)
197 | }
198 | }
199 | return results
200 | }
201 | }
202 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Binary Tree/LCTreePreOrderTraverse.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreePreOrderTraverse.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 4/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Binary Tree Preorder Traversal
10 | // http://www.lintcode.com/en/problem/binary-tree-preorder-traversal
11 | class LCTreePreOrderTraverse {
12 | class func enumerateTreeNode(node: LCTreeNode?, result: Int -> Void) {
13 | if let current = node {
14 | result(current.val)
15 | enumerateTreeNode(current.left, result: result)
16 | enumerateTreeNode(current.right, result: result)
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Integer Array/LCPlusOne.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCPlusOne.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | Plus One
11 | http://www.lintcode.com/en/problem/plus-one/
12 |
13 | Given a non-negative number represented as an array of digits, plus one to the number.
14 |
15 | The digits are stored such that the most significant digit is at the head of the list.
16 |
17 | Example
18 | Given [1,2,3] which represents 123, return [1,2,4].
19 | Given [9,9,9] which represents 999, return [1,0,0,0].
20 |
21 | */
22 | struct LCPlusOne {
23 | /**
24 | Based on the an array of digits, it returns the array with plus one
25 |
26 | - parameter digits: digits a number represented as an array of digits
27 |
28 | - returns: the result
29 | */
30 | static func plusOne(digits: [Int]) -> [Int] {
31 | var digits = digits
32 | var carries = 1
33 | var index = digits.count - 1;
34 |
35 | while index >= 0 && carries > 0 {
36 | let sum = digits[index] + carries
37 | digits[index] = sum % 10
38 | carries = sum / 10
39 | index -= 1
40 | }
41 |
42 | if carries == 0 {
43 | return digits
44 | }
45 |
46 | var result: [Int] = []
47 | result.append(1)
48 |
49 | for i in 1 ..< digits.count + 1 {
50 | result.append(digits[i - 1])
51 | }
52 |
53 | return result
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Integer Array/LCRemoveDuplicates.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveDuplicates.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 27/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Remove Duplicates from Sorted Array
10 | // http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-array/
11 | class LCRemoveDuplicates {
12 | /**
13 | * @param A: a array of integers
14 | * @return : return an integer
15 | */
16 | class func removeDuplicates(nums: [Int]) -> Int {
17 | if nums.count == 0 {
18 | return 0
19 | }
20 |
21 | var size = 0
22 | var mutableNums = nums
23 |
24 | for i in 0.. Int {
18 | var mutableA = A
19 |
20 | var i = 0
21 | var pointer = mutableA.count - 1
22 |
23 | while i <= pointer {
24 | if mutableA[i] == elem {
25 | mutableA[i] = mutableA[pointer]
26 | pointer-=1
27 | } else {
28 | i+=1
29 | }
30 | }
31 |
32 | return pointer + 1
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Integer Array/LCSubarraySum.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCSubarraySum.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 27/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Subarray Sum
10 | // http://www.lintcode.com/en/problem/subarray-sum/
11 | class LCSubarraySum {
12 | /**
13 | * @param nums: A list of integers
14 | * @return: A list of integers includes the index of the first number
15 | * and the index of the last number
16 | */
17 | class func subarraySum(nums: [Int]) -> [Int] {
18 | let len = nums.count
19 | var ans = [Int]()
20 | var map = [Int : Int]()
21 |
22 | map[0] = -1
23 |
24 | var sum = 0
25 | for i in 0.. [Int] {
29 | var map = [Int: Int]()
30 |
31 | for i in 0 ..< numbers.count {
32 | if let value = map[numbers[i]] {
33 | return [value, i]
34 | } else {
35 | map[target - numbers[i]] = i
36 | }
37 | }
38 |
39 | return []
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Integer/LCReverseInteger.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCReverseInteger.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 17/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Reverse Integer
10 | // http://www.lintcode.com/en/problem/reverse-integer/
11 |
12 | /**
13 | Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
14 |
15 | Example
16 | Given x = 123, return 321
17 |
18 | Given x = -123, return -321
19 |
20 | */
21 |
22 | struct LCReverseInteger {
23 | static func reverseInteger(num: Int) -> Int {
24 | var num = num;
25 | var reversed = 0
26 |
27 | while num != 0 {
28 | let temp = reversed * 10 + num % 10
29 | num = num / 10
30 |
31 | if temp / 10 != reversed {
32 | reversed = 0
33 | break
34 | }
35 |
36 | reversed = temp
37 | }
38 |
39 | return reversed
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Linked List/Data Structure/LCLinkedList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCLinkedList.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import UIKit
10 |
11 | class LCLinkedList: NSObject {
12 |
13 | class func linkedList(values: [Int]) -> LCLinkedListNode {
14 | let root = LCLinkedListNode.init(val: values[0])
15 | var current = root
16 | for i in 1.. Bool {
34 | var current1: LCLinkedListNode? = node1
35 | var current2: LCLinkedListNode? = node2
36 |
37 | while current1 != nil {
38 | if current2 == nil {
39 | return false
40 | }
41 |
42 | if current1!.val != current2!.val {
43 | return false
44 | }
45 |
46 | current1 = current1!.next
47 | current2 = current2!.next
48 | }
49 |
50 | if current2 != nil {
51 | return false
52 | }
53 |
54 | return true
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Linked List/Data Structure/LCLinkedListNode.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCLinkedListNode.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | class LCLinkedListNode: NSObject {
12 | var val: Int
13 | var next: LCLinkedListNode?
14 |
15 | init(val: Int) {
16 | self.val = val
17 | }
18 |
19 | init(val: Int, next: LCLinkedListNode) {
20 | self.val = val
21 | self.next = next
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Linked List/LCAddTwoNumbers.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCAddTwoNumbers.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 10/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Add Two Numbers
10 | // http://www.lintcode.com/en/problem/add-two-numbers/
11 | class LCAddTwoNumbers {
12 | class func addTwoNumbers(l1: LCLinkedListNode, l2: LCLinkedListNode) -> LCLinkedListNode {
13 | var currentL1: LCLinkedListNode? = l1
14 | var currentL2: LCLinkedListNode? = l2
15 |
16 | let head = LCLinkedListNode.init(val: 0)
17 | var point = head
18 |
19 | var carry = 0
20 |
21 | while currentL1 != nil && currentL2 != nil {
22 | let sum = carry + currentL1!.val + currentL2!.val
23 | point.next = LCLinkedListNode.init(val: sum % 10)
24 | carry = sum / 10
25 | currentL1 = currentL1!.next
26 | currentL2 = currentL2!.next
27 | point = point.next!
28 | }
29 |
30 | while currentL1 != nil {
31 | let sum = carry + currentL1!.val
32 | point.next = LCLinkedListNode(val: sum % 10)
33 | carry = sum / 10
34 | currentL1 = currentL1!.next
35 | point = point.next!
36 | }
37 |
38 | while currentL2 != nil {
39 | let sum = carry + currentL2!.val
40 | point.next = LCLinkedListNode(val: sum % 10)
41 | carry = sum / 10
42 | currentL2 = currentL2!.next
43 | point = point.next!
44 | }
45 |
46 | if carry != 0 {
47 | point.next = LCLinkedListNode.init(val: carry)
48 | }
49 |
50 | return head.next!
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Linked List/LCMergeTwoLists.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCMergeTwoLists.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Merge Two Sorted Lists
10 | // http://www.lintcode.com/en/problem/merge-two-sorted-lists/
11 | class LCMergeTwoLists {
12 | class func mergeTwoLists(l1: LCLinkedListNode, l2: LCLinkedListNode) -> LCLinkedListNode {
13 | var mutableL1: LCLinkedListNode? = l1
14 | var mutableL2: LCLinkedListNode? = l2
15 |
16 | let newList = LCLinkedListNode.init(val: 0)
17 | var temp = newList
18 |
19 | while mutableL1 != nil && mutableL2 != nil {
20 | if (mutableL1!.val < mutableL2!.val) {
21 | temp.next = mutableL1!
22 | mutableL1 = mutableL1!.next
23 | } else {
24 | temp.next = mutableL2!
25 | mutableL2 = mutableL2!.next
26 | }
27 |
28 | temp = temp.next!
29 | }
30 |
31 | if (mutableL1 != nil) {
32 | temp.next = mutableL1!
33 | } else {
34 | temp.next = mutableL2!
35 | }
36 |
37 | return newList.next!
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Linked List/LCRemoveDuplicatesFromList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveDuplicatesFromList.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Remove Duplicates from Sorted List
10 | // http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-list/
11 | class LCRemoveDuplicatesFromList {
12 | /**
13 | * @param ListNode head is the head of the linked list
14 | * @return: ListNode head of linked list
15 | */
16 | class func deleteDuplicates(head: LCLinkedListNode) -> LCLinkedListNode {
17 | var node = head
18 |
19 | while node.next != nil {
20 | if node.val == node.next!.val {
21 | node.next = node.next!.next
22 | } else {
23 | node = node.next!
24 | }
25 | }
26 |
27 | return head
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Linked List/LCRemoveNodeFromList.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveNodeFromList.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Remove Nth Node From End of List
10 | // http://www.lintcode.com/en/problem/remove-nth-node-from-end-of-list/
11 | class LCRemoveNodeFromList {
12 | /**
13 | * @param head: The first node of linked list.
14 | * @param n: An integer.
15 | * @return: The head of linked list.
16 | */
17 | class func removeNthFromEnd(head: LCLinkedListNode, n: Int) -> LCLinkedListNode? {
18 | if n <= 0 {
19 | return nil
20 | }
21 |
22 | let tempStart = LCLinkedListNode.init(val: 0)
23 | tempStart.next = head
24 |
25 | var preDelete: LCLinkedListNode? = tempStart
26 | var current: LCLinkedListNode? = head
27 | for _ in 0.. LCLinkedListNode {
17 | var prev: LCLinkedListNode? = nil
18 | var current: LCLinkedListNode? = head
19 | while current != nil {
20 | let temp = current!.next
21 | current!.next = prev
22 | prev = current
23 | current = temp
24 | }
25 |
26 | return prev!
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Math & Bit Manipulation/LCCheckPowerOf2.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCCheckPowerOf2.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // O(1) Check Power of 2
10 | // http://www.lintcode.com/en/problem/o1-check-power-of-2/
11 | class LCCheckPowerOf2 {
12 | /*
13 | * @param n: An integer
14 | * @return: True or false
15 | */
16 | class func checkPowerOf2(n: Int) -> Bool {
17 | if n <= 0 {
18 | return false
19 | }
20 | return n & (n - 1) == 0
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Math & Bit Manipulation/LCFlipBits.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFlipBits.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Flip bits
10 | // http://www.lintcode.com/en/problem/flip-bits/
11 |
12 | class LCFlipBits {
13 | /**
14 | *@param a, b: Two integer
15 | *return: An integer
16 | */
17 | class func bitSwapRequired(a: Int, b: Int) -> Int {
18 | var count = 0
19 |
20 | var c = a ^ b
21 | while c != 0 {
22 | count += c & 1
23 | c = c >> 1
24 | }
25 |
26 | return count
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Math & Bit Manipulation/LCUniquePaths.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCUniquePaths.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Unique Paths
10 | // http://www.lintcode.com/en/problem/unique-paths/
11 | class LCUniquePaths {
12 | /**
13 | * @param n, m: positive integer (1 <= n ,m <= 100)
14 | * @return an integer
15 | */
16 | class func uniquePaths(m: Int, n: Int) -> Int {
17 | if m == 0 || n == 0 {
18 | return 0
19 | }
20 |
21 | var sum = Array(count: m, repeatedValue: Array(count: n, repeatedValue: 0))
22 |
23 | for i in 0.. [[Int]] {
17 | var rst: [[Int]] = []
18 |
19 | if num.count == 0 {
20 | return rst
21 | }
22 |
23 | var list: [Int] = []
24 | helper(&rst, list: &list, num: num)
25 | return rst
26 | }
27 |
28 | private func helper(inout rst: [[Int]], inout list: [Int], num: [Int]) {
29 | if list.count == num.count {
30 | rst.append(list)
31 | return
32 | }
33 |
34 | for i in 0 ..< num.count {
35 | if list.contains(num[i]) {
36 | continue
37 | }
38 |
39 | list.append(num[i])
40 | helper(&rst, list: &list, num: num)
41 | list.removeAtIndex(list.count - 1)
42 | }
43 | }
44 | }
45 |
46 | // Non-Recursion
47 | extension LCPermutations {
48 | class func permute(nums: [Int]) -> [[Int]] {
49 | var permutations: [[Int]] = []
50 |
51 | if (nums.count == 0) {
52 | return permutations
53 | }
54 |
55 | let n = nums.count
56 | var stack: [Int] = []
57 |
58 | stack.append(-1)
59 |
60 | while stack.count != 0 {
61 | let last = stack[stack.count - 1]
62 | stack.removeAtIndex(stack.count - 1)
63 |
64 | // increase the last number
65 | var next = -1
66 |
67 | for i in last + 1 ..< n {
68 | if !stack.contains(i) {
69 | next = i
70 | break
71 | }
72 | }
73 |
74 | if next == -1 {
75 | continue
76 | }
77 |
78 | // generate the next permutation
79 | stack.append(next)
80 |
81 | for i in 0 ..< n {
82 | if !stack.contains(i) {
83 | stack.append(i)
84 | }
85 | }
86 |
87 | // copy to permutations set
88 | var permutation: [Int] = []
89 |
90 | for i in 0 ..< n {
91 | permutation.append(nums[stack[i]])
92 | }
93 |
94 | permutations.append(permutation)
95 | }
96 |
97 | return permutations
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Search & Recursion/LCPermutationsII.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCPermutationsII.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Permutations II
12 | // http://www.lintcode.com/en/problem/permutations-ii/
13 | class LCPermutationsII: NSObject {
14 | private var result: [[Int]]
15 | private var list: [Int]
16 | private var visited: [Int]
17 | private var sortedNum: [Int]
18 |
19 | override init() {
20 | result = []
21 | list = []
22 | visited = []
23 | sortedNum = []
24 | super.init()
25 | }
26 |
27 | func permuteUnique(num: [Int]) -> [[Int]] {
28 | if num.count == 0 {
29 | return result
30 | }
31 |
32 | sortedNum = num.sort()
33 | visited = Array.init(count: num.count, repeatedValue: 0)
34 |
35 | helper()
36 |
37 | return result
38 | }
39 |
40 | private func helper() {
41 | if list.count == sortedNum.count {
42 | result.append(list)
43 | return
44 | }
45 |
46 | for i in 0 ..< sortedNum.count {
47 | if visited[i] == 1 || (i != 0 && sortedNum[i] == sortedNum[i - 1] && visited[i - 1] == 0) {
48 | continue
49 | }
50 |
51 | visited[i] = 1
52 | list.append(sortedNum[i])
53 | helper()
54 | list.removeAtIndex(list.count - 1)
55 | visited[i] = 0
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/Search & Recursion/LCSubsets.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCSubsets.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 11/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // Subsets
10 | // http://www.lintcode.com/en/problem/subsets/
11 | class LCSubsets {
12 | // Non Recursion
13 | class func subsets(nums: [Int]) -> [[Int]] {
14 | var result: [[Int]] = []
15 | let n = nums.count
16 | var sorted = nums
17 | sorted.sortInPlace()
18 |
19 | // 1 << n is 2^n
20 | // each subset equals to an binary integer between 0 .. 2^n - 1
21 | // 0 -> 000 -> []
22 | // 1 -> 001 -> [1]
23 | // 2 -> 010 -> [2]
24 | // ..
25 | // 7 -> 111 -> [1,2,3]
26 | for i in 0 ..< 1<) -> Int {
21 | if dict.count == 0 {
22 | return 0
23 | }
24 |
25 | if start == end {
26 | return 1
27 | }
28 |
29 | dict.insert(start)
30 | dict.insert(end)
31 |
32 | var hashSet = Set()
33 | let queue = LCQueue()
34 | queue.enqueue(start)
35 | hashSet.insert(start)
36 |
37 | var length = 1
38 | while !queue.isEmpty() {
39 | length += 1
40 | let size = queue.size()
41 | for _ in 0 ..< size {
42 | if let word = queue.dequeue() {
43 | for nextWord in getNextWords(word, dict: dict) {
44 | if hashSet.contains(nextWord) {
45 | continue
46 | }
47 |
48 | if nextWord == end {
49 | return length
50 | }
51 |
52 | hashSet.insert(nextWord)
53 | queue.enqueue(nextWord)
54 | }
55 | }
56 | }
57 | }
58 |
59 | return 0
60 | }
61 |
62 | // get connections with given word.
63 | // for example, given word = 'hot', dict = {'hot', 'hit', 'hog'}
64 | // it will return ['hit', 'hog']
65 | private func getNextWords(word: String, dict: Set) -> [String] {
66 | var nextWords: [String] = []
67 | let charA: Character = "a"
68 | let charZ: Character = "z"
69 | for c in charA.unicodeScalarCodePoint() ... charZ.unicodeScalarCodePoint() {
70 | var i = 0
71 | for character in word.characters {
72 | if c == character.unicodeScalarCodePoint() {
73 | continue
74 | }
75 |
76 | let nextWord = replace(word, index: i, c: Character(UnicodeScalar(c)))
77 |
78 | if dict.contains(nextWord) {
79 | nextWords.append(nextWord)
80 | }
81 |
82 | i += 1
83 | }
84 | }
85 |
86 | return nextWords
87 | }
88 |
89 | // replace character of a string at given index to a given character
90 | // return a new string
91 | private func replace(s: String, index: Int, c: Character) -> String {
92 | var characters = Array(s.characters)
93 | characters[index] = c
94 | return String(characters)
95 | }
96 |
97 | }
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/String/LCAnagrams.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCAnagrams.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 25/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Two Strings Are Anagrams
12 | // http://www.lintcode.com/en/problem/two-strings-are-anagrams/
13 | class LCAnagrams: NSObject {
14 | /**
15 | * @param stringA: The first string
16 | * @param stringB: The second string
17 | * @return true or false
18 | */
19 | class func anagram(stringA: String, stringB: String) -> Bool {
20 | if stringA.characters.count != stringB.characters.count {
21 | return false
22 | }
23 |
24 | var dictionary = [String : Int]()
25 |
26 | for character in stringA.characters {
27 | if var count = dictionary[String(character)] {
28 | count = count + 1
29 | dictionary[String(character)] = count
30 | } else {
31 | dictionary[String(character)] = 1
32 | }
33 |
34 | }
35 |
36 | for character in stringB.characters {
37 | if var count = dictionary[String(character)] {
38 | count = count - 1
39 | dictionary[String(character)] = count
40 | if count < 0 {
41 | return false
42 | }
43 |
44 | } else {
45 | return false
46 | }
47 |
48 | }
49 |
50 | return true
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/String/LCCompareStrings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCCompareStrings.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 26/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | // Compare Strings
12 | // http://www.lintcode.com/en/problem/compare-strings/
13 | class LCCompareStrings: NSObject {
14 | /**
15 | * @param A : A string includes Upper Case letters
16 | * @param B : A string includes Upper Case letter
17 | * @return : if string A contains all of the characters in B return true else return false
18 | */
19 | class func compareStrings(A: String, B: String) -> Bool {
20 | var dictionary = [String : Int]()
21 |
22 | for character in A.characters {
23 | if var count = dictionary[String(character)] {
24 | count = count + 1
25 | dictionary[String(character)] = count
26 | } else {
27 | dictionary[String(character)] = 1
28 | }
29 | }
30 |
31 | for character in B.characters {
32 | if var count = dictionary[String(character)] {
33 | count = count - 1
34 | dictionary[String(character)] = count
35 | if (count < 0) {
36 | return false
37 | }
38 | } else {
39 | return false
40 | }
41 | }
42 |
43 | return true
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/InterviewInSwift/LintCode/String/LCStrStr.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCStrStr.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 26/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | // strStr
10 | // http://www.lintcode.com/en/problem/strstr/
11 | class LCStrStr {
12 | /**
13 | * Returns a index to the first occurrence of target in source,
14 | * or -1 if target is not part of source.
15 | * @param source string to be scanned.
16 | * @param target string containing the sequence of characters to match.
17 | */
18 | class func strStr(source: String, target: String) -> Int {
19 | for i in 0..
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 | UIRequiredDeviceCapabilities
26 |
27 | armv7
28 |
29 | UISupportedInterfaceOrientations
30 |
31 | UIInterfaceOrientationPortrait
32 | UIInterfaceOrientationLandscapeLeft
33 | UIInterfaceOrientationLandscapeRight
34 |
35 | UISupportedInterfaceOrientations~ipad
36 |
37 | UIInterfaceOrientationPortrait
38 | UIInterfaceOrientationPortraitUpsideDown
39 | UIInterfaceOrientationLandscapeLeft
40 | UIInterfaceOrientationLandscapeRight
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/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 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC006ZigZagConversion.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC006ZigZagConversion.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | /**
10 | 6. ZigZag Conversion
11 | https://leetcode.com/problems/zigzag-conversion/
12 |
13 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
14 |
15 | P A H N
16 | A P L S I I G
17 | Y I R
18 | And then read line by line: "PAHNAPLSIIGYIR"
19 | Write the code that will take a string and make this conversion given a number of rows:
20 |
21 | string convert(string text, int nRows);
22 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
23 |
24 | */
25 |
26 | struct LC006ZigZagConversion {
27 | // t = O(N), s = O(N)
28 | static func convert(string: String, numberOfRows: Int) -> String {
29 | return ""
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC008StringToIntegerAtoiTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC008StringToIntegerAtoiTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 19/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC008StringToIntegerAtoiTest: XCTestCase {
12 | func testAtoi_001() {
13 | let input: String = "123"
14 | let expected: Int = 123
15 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
16 | }
17 | func testAtoi_002() {
18 | let input: String = " 123"
19 | let expected: Int = 123
20 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
21 | }
22 | func testAtoi_003() {
23 | let input: String = " +123"
24 | let expected: Int = 123
25 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
26 | }
27 | func testAtoi_004() {
28 | let input: String = "-123"
29 | let expected: Int = -123
30 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
31 | }
32 | func testAtoi_005() {
33 | let input: String = " -123"
34 | let expected: Int = -123
35 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
36 | }
37 | func testAtoi_006() {
38 | let input: String = String(Int.max)
39 | let expected: Int = 9223372036854775807
40 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
41 | }
42 | func testAtoi_007() {
43 | let input: String = " 9223372036854775808"
44 | let expected: Int = 9223372036854775807
45 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
46 | }
47 | func testAtoi_008() {
48 | let input: String = " 9223372036854775806"
49 | let expected: Int = 9223372036854775806
50 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
51 | }
52 | func testAtoi_009() {
53 | let input: String = String(Int.min)
54 | let expected: Int = -9223372036854775808
55 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
56 | }
57 | func testAtoi_010() {
58 | let input: String = " -9223372036854775809"
59 | let expected: Int = -9223372036854775808
60 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
61 | }
62 | func testAtoi_011() {
63 | let input: String = " -9223372036854775806"
64 | let expected: Int = -9223372036854775806
65 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
66 | }
67 | func testAtoi_012() {
68 | let input: String = " 123- "
69 | let expected: Int = 123
70 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
71 | }
72 | func testAtoi_013() {
73 | let input: String = " -9223372036854775808-"
74 | let expected: Int = -9223372036854775808
75 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
76 | }
77 | func testAtoi_014() {
78 | let input: String = " -9223372036854775807-"
79 | let expected: Int = -9223372036854775807
80 | XCTAssert(LC008StringToIntegerAtoi.atoi(input) == expected)
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC009PalindromeNumberTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC009PalindromeNumberTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 19/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC009PalindromeNumberTest: XCTestCase {
12 | func testIsPalindrome_001() {
13 | let input: Int = -121
14 | XCTAssertFalse(LC009PalindromeNumber.isPalindrome(input))
15 | }
16 |
17 | func testIsPalindrome_002() {
18 | let input: Int = 121
19 | XCTAssertTrue(LC009PalindromeNumber.isPalindrome(input))
20 | }
21 |
22 | func testIsPalindrome_003() {
23 | let input: Int = 0
24 | XCTAssertTrue(LC009PalindromeNumber.isPalindrome(input))
25 | }
26 |
27 | func testIsPalindrome_004() {
28 | let input: Int = Int.max
29 | XCTAssertFalse(LC009PalindromeNumber.isPalindrome(input))
30 | }
31 | func testIsPalindrome_005() {
32 | let input: Int = Int.min
33 | XCTAssertFalse(LC009PalindromeNumber.isPalindrome(input))
34 | }
35 | func testIsPalindrome_006() {
36 | let input: Int = 1999999999999999999
37 | XCTAssertFalse(LC009PalindromeNumber.isPalindrome(input))
38 | }
39 | func testIsPalindrome_007() {
40 | let input: Int = -1999999999999999999
41 | XCTAssertFalse(LC009PalindromeNumber.isPalindrome(input))
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC013RomanToIntegerTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC013RomanToIntegerTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 20/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC013RomanToIntegerTest: XCTestCase {
12 | func testRomanToInt_001() {
13 | let input: String = "I"
14 | let expected: Int = 1
15 | XCTAssert(LC013RomanToInteger.romanToInt(input) == expected)
16 | }
17 | func testRomanToInt_002() {
18 | let input: String = "MMMCMXCIX"
19 | let expected: Int = 3999
20 | XCTAssert(LC013RomanToInteger.romanToInt(input) == expected)
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC022GenerateParenthesesTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC022GenerateParenthesesTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 21/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC022GenerateParenthesesTest: XCTestCase {
12 | func testGenerateParenthesis_001() {
13 | let input: Int = 1
14 | let expected: [String] = ["()"]
15 | XCTAssert(expected == LC022GenerateParentheses.generateParenthesis(input))
16 | }
17 |
18 | func testGenerateParenthesis_002() {
19 | let input: Int = 0
20 | let expected: [String] = [""]
21 | XCTAssert(expected == LC022GenerateParentheses.generateParenthesis(input))
22 | }
23 |
24 | func testGenerateParenthesis_003() {
25 | let input: Int = 3
26 | let expected: [String] = ["((()))", "(()())", "(())()", "()(())", "()()()"]
27 | XCTAssert(compareUnordered(expected, array2: LC022GenerateParentheses.generateParenthesis(input)))
28 | }
29 |
30 | func compareUnordered(array1: [String], array2: [String]) -> Bool {
31 | if array1.count != array2.count {
32 | return false
33 | }
34 |
35 | let set1 = Set(array1)
36 | let set2 = Set(array2)
37 |
38 | return set1 == set2
39 | }
40 |
41 | }
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC050PowXNTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC050PowXNTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC050PowXNTest: XCTestCase {
12 |
13 | static let allowanceError = 0.01
14 |
15 | func testMyPow_001() {
16 | XCTAssert((LC050PowXN.myPow(987.654, n: 4) - pow(987.654, 4)) < LC050PowXNTest.allowanceError)
17 | }
18 |
19 | func testMyPow_002() {
20 | XCTAssert((LC050PowXN.myPow(987.654, n: 0) - pow(987.654, 0)) < LC050PowXNTest.allowanceError)
21 | }
22 |
23 | func testMyPow_003() {
24 | XCTAssert((LC050PowXN.myPow(-987.654, n: 3) - pow(-987.654, 3)) < LC050PowXNTest.allowanceError)
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC058LengthOfLastWordTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC058LengthOfLastWordTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC058LengthOfLastWordTest: XCTestCase {
12 | func testLengthOfLastWord() {
13 | XCTAssert(LC058LengthOfLastWord.lengthOfLastWord("Hello World") == 5)
14 | XCTAssert(LC058LengthOfLastWord.lengthOfLastWord("") == 0)
15 | XCTAssert(LC058LengthOfLastWord.lengthOfLastWord(" Hello ") == 5)
16 | XCTAssert(LC058LengthOfLastWord.lengthOfLastWord(" Hello a") == 1)
17 | XCTAssert(LC058LengthOfLastWord.lengthOfLastWord(" asd a baddsd asddddf asdsdfe wedr asdfddas dfae ") == 4)
18 | XCTAssert(LC058LengthOfLastWord.lengthOfLastWord("abcde") == 5)
19 |
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC075SortColorsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC075SortColorsTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 22/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC075SortColorsTest: XCTestCase {
12 | func testSortColor() {
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 | LC075SortColors.sortColors(&input)
16 | XCTAssert(input == expected)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC077CombinationsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC077CombinationsTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 22/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC077CombinationsTest: XCTestCase {
12 | func testCombine_001() {
13 | let input: [Int] = [4, 2]
14 | let expected: [[Int]] = [
15 | [2,4],
16 | [3,4],
17 | [2,3],
18 | [1,2],
19 | [1,3],
20 | [1,4],
21 | ]
22 | comparehelper(LC077Combinations.combine(input[0], k: input[1]), inputB: expected)
23 | comparehelper(LC077Combinations.combineRecursion(input[0], k: input[1]), inputB: expected)
24 | }
25 |
26 | func testCombine_002() {
27 | let input: [Int] = [1, 1]
28 | let expected: [[Int]] = [
29 | [1]
30 | ]
31 | XCTAssert(LC077Combinations.combine(input[0], k: input[1]) == expected)
32 | XCTAssert(LC077Combinations.combineRecursion(input[0], k: input[1]) == expected)
33 | }
34 |
35 | func testCombine_003() {
36 | let input: [Int] = [2, 1]
37 | let expected: [[Int]] = [
38 | [1],
39 | [2]
40 | ]
41 | XCTAssert(LC077Combinations.combine(input[0], k: input[1]) == expected)
42 | XCTAssert(LC077Combinations.combineRecursion(input[0], k: input[1]) == expected)
43 | }
44 |
45 | func comparehelper(inputA: [[Int]], inputB: [[Int]]) -> Bool {
46 | if inputA.count != inputB.count {
47 | return false
48 | }
49 |
50 | for array in inputA {
51 | XCTAssertTrue(inputB.contains {
52 | $0 == array
53 | })
54 |
55 | }
56 |
57 | return true
58 | }
59 |
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC100SameTreeTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC100SameTreeTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 |
12 | class LC100SameTreeTest: XCTestCase {
13 | /**
14 | * 1
15 | * / \
16 | * 2 3
17 | * / \
18 | * 4 5
19 | */
20 | static let tree1: LCTreeNode? = LCTreeNodeHelper.createTreeNode("1,2,3,4,5,#,#")
21 | static let tree2: LCTreeNode? = LCTreeNodeHelper.createTreeNode("1,2,3,4,5,6,#")
22 | static let tree3: LCTreeNode? = LCTreeNodeHelper.createTreeNode("1,2,3,4,5,#,#")
23 |
24 | func testIsSame() {
25 | XCTAssert(case1().expectedResult == LC100SameTree.isSameTree(case1().inputA, node2: case1().inputB))
26 | XCTAssert(case2().expectedResult == LC100SameTree.isSameTree(case2().inputA, node2: case2().inputB))
27 | }
28 |
29 | }
30 |
31 | extension LC100SameTreeTest {
32 | func case1() -> LC100SameTreeTestCaseModel {
33 | return LC100SameTreeTestCaseModel.init(inputA: LC100SameTreeTest.tree1, inputB: LC100SameTreeTest.tree3, expectedResult: true)
34 | }
35 |
36 | func case2() -> LC100SameTreeTestCaseModel {
37 | return LC100SameTreeTestCaseModel.init(inputA: LC100SameTreeTest.tree1, inputB: LC100SameTreeTest.tree2, expectedResult: false)
38 | }
39 |
40 | }
41 |
42 | class LC100SameTreeTestCaseModel: NSObject {
43 | var inputA: LCTreeNode?
44 | var inputB: LCTreeNode?
45 | var expectedResult: Bool
46 |
47 | init(inputA: LCTreeNode?, inputB: LCTreeNode?, expectedResult: Bool) {
48 | self.inputA = inputA
49 | self.inputB = inputB
50 | self.expectedResult = expectedResult
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC205IsomorphicStringsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC205IsomorphicStringsTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 15/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC205IsomorphicStringsTest: XCTestCase {
12 | /**
13 | For example,
14 | Given "egg", "add", return true.
15 |
16 | Given "foo", "bar", return false.
17 |
18 | Given "paper", "title", return true.
19 | */
20 | func testIsIsomorphic() {
21 | XCTAssertTrue(LC205IsomorphicStrings.isIsomorphic("egg", target: "add"))
22 | XCTAssertFalse(LC205IsomorphicStrings.isIsomorphic("foo", target: "bar"))
23 | XCTAssertTrue(LC205IsomorphicStrings.isIsomorphic("paper", target: "title"))
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC244WordDistanceIITest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC244WordDistanceIITest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC244WordDistanceIITest: XCTestCase {
12 | /**
13 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
14 |
15 | Given word1 = “coding”, word2 = “practice”, return 3.
16 | Given word1 = "makes", word2 = "coding", return 1.
17 | */
18 | func testLC244WordDistanceII() {
19 | let words = ["practice", "makes", "perfect", "coding", "makes"]
20 | let distance = LC244WordDistanceII.init(words: words)
21 |
22 | XCTAssert(distance.shortest("coding", word2: "practice") == 3)
23 | XCTAssert(distance.shortest("makes", word2: "coding") == 1)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LeetCode/LC367ValidPerfectSquareTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LC367ValidPerfectSquareTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LC367ValidPerfectSquareTest: XCTestCase {
12 | func testIsPerfectSquare() {
13 | XCTAssertTrue(LC367ValidPerfectSquare.isPerfectSquare(16))
14 | XCTAssertTrue(LC367ValidPerfectSquare.isPerfectSquare(100))
15 | XCTAssertFalse(LC367ValidPerfectSquare.isPerfectSquare(14))
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCAddTwoNumbersTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCAddTwoNumbersTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 10/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCAddTwoNumbersTest: XCTestCase {
12 | /**
13 | * Given 7->1->6 + 5->9->2. That is, 617 + 295.
14 | * Return 2->1->9. That is 912.
15 | * Given 3->1->5 and 5->9->2, return 8->0->8.
16 | */
17 | func testAddTwoNumbers() {
18 | let test1 = LCAddTwoNumbersTestCaseModel.init(l1: [7, 1, 6], l2: [5, 9, 2], result: [2, 1, 9])
19 | let test2 = LCAddTwoNumbersTestCaseModel.init(l1: [3, 1, 5], l2: [5, 9, 2], result: [8, 0, 8])
20 |
21 | XCTAssertTrue(LCLinkedList.compare(test1.expectedResult, node2: LCAddTwoNumbers.addTwoNumbers(test1.inputLinkedList1, l2: test1.inputLinkedList2)))
22 | XCTAssertTrue(LCLinkedList.compare(test2.expectedResult, node2: LCAddTwoNumbers.addTwoNumbers(test2.inputLinkedList1, l2: test2.inputLinkedList2)))
23 | }
24 | }
25 |
26 | class LCAddTwoNumbersTestCaseModel: NSObject {
27 | var inputLinkedList1: LCLinkedListNode
28 | var inputLinkedList2: LCLinkedListNode
29 | var expectedResult: LCLinkedListNode
30 |
31 | init(l1: [Int], l2: [Int], result: [Int]) {
32 | inputLinkedList1 = LCLinkedList.linkedList(l1)
33 | inputLinkedList2 = LCLinkedList.linkedList(l2)
34 | expectedResult = LCLinkedList.linkedList(result)
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCAnagramsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCAnagramsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 26/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | // Given s = "abcd", t = "dcab", return true.
12 | // Given s = "ab", t = "ab", return true.
13 | // Given s = "ab", t = "ac", return false.
14 | class LCAnagramsTest: XCTestCase {
15 | override func setUp() {
16 | super.setUp()
17 | // Put setup code here. This method is called before the invocation of each test method in the class.
18 | }
19 |
20 | override func tearDown() {
21 | // Put teardown code here. This method is called after the invocation of each test method in the class.
22 | super.tearDown()
23 | }
24 |
25 | func testAnagram() {
26 | let s1 = "abcd"
27 | let t1 = "dcab"
28 | XCTAssertTrue(LCAnagrams.anagram(s1, stringB: t1))
29 |
30 | let s2 = "ab"
31 | let t2 = "ab"
32 | XCTAssertTrue(LCAnagrams.anagram(s2, stringB: t2))
33 |
34 | let s3 = "ab"
35 | let t3 = "ac"
36 | XCTAssertFalse(LCAnagrams.anagram(s3, stringB: t3))
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCBSTSearchRangeTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCBSTSearchRangeTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 7/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCBSTSearchRangeTest: XCTestCase {
12 | /**
13 | * If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].
14 | *
15 | * 20
16 | * / \
17 | * 8 22
18 | * / \
19 | * 4 12
20 | */
21 |
22 | func testSearchRange() {
23 | let searchRange = LCBSTSearchRange()
24 | let testCase1 = TestCase1()
25 | let result1 = searchRange.searchRange(testCase1.tree, k1: testCase1.k1, k2: testCase1.k2)
26 | XCTAssertTrue(result1 == testCase1.expectedTreeResult)
27 | }
28 |
29 |
30 | }
31 |
32 | class TestCase1: NSObject {
33 | var tree: LCTreeNode {
34 | get {
35 | return LCTreeNodeHelper.createTreeNode("20,8,22,4,12,#,#")
36 | }
37 | }
38 |
39 | var expectedTreeResult: [Int] {
40 | get {
41 | return [12, 20, 22]
42 | }
43 | }
44 |
45 | var k1 = 10
46 | var k2 = 22
47 | }
48 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCBSTValidationTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCBSTValidationTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 5/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCBSTValidationTest: XCTestCase {
12 | /**
13 | * An example:
14 | *
15 | * 2
16 | * / \
17 | * 1 4
18 | * / \
19 | * 3 5
20 | * The above binary tree is serialized as {2,1,4,#,#,3,5} (in level order).
21 | */
22 | func testIsValidBST() {
23 | let tree1 = LCTreeNodeHelper.createTreeNode("2,1,4,#,#,3,5")
24 | let tree2 = LCTreeNodeHelper.createTreeNode("2,1,4,#,#,5,3")
25 | let validation = LCBSTValidation.init()
26 | XCTAssertTrue(validation.isValidBST(tree1))
27 | XCTAssertFalse(validation.isValidBST(tree2))
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCBalancedTreeTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCBalancedTreeTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 30/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCBalancedTreeTest: XCTestCase {
12 | /**
13 | * Given binary tree A = {3,9,20,#,#,15,7}, B = {3,#,20,15,7}
14 | *
15 | * A) 3 B) 3
16 | * / \ \
17 | * 9 20 20
18 | * / \ / \
19 | * 15 7 15 7
20 | *
21 | * The binary tree A is a height-balanced binary tree, but B is not.
22 | */
23 | func testIsBalanced() {
24 | let testA = LCTreeNodeHelper.createTreeNode("3,9,20,#,#,15,7")
25 | let testB = LCTreeNodeHelper.createTreeNode("3,#,20,15,7")
26 |
27 | XCTAssertTrue(LCBalancedTree.isBalanced(testA))
28 | XCTAssertFalse(LCBalancedTree.isBalanced(testB))
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCCheckPowerOf2Test.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCCheckPowerOf2Test.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCCheckPowerOf2Test: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // For n=4, return true;
24 | // For n=5, return false;
25 | func testCheckPowerOf2() {
26 | XCTAssertTrue(LCCheckPowerOf2.checkPowerOf2(4))
27 | XCTAssertFalse(LCCheckPowerOf2.checkPowerOf2(5))
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCCompareStringsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCCompareStringsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 26/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | // For A = "ABCD", B = "ACD", return true.
12 | // For A = "ABCD", B = "AABC", return false.
13 | class LCCompareStringsTest: XCTestCase {
14 |
15 | override func setUp() {
16 | super.setUp()
17 | // Put setup code here. This method is called before the invocation of each test method in the class.
18 | }
19 |
20 | override func tearDown() {
21 | // Put teardown code here. This method is called after the invocation of each test method in the class.
22 | super.tearDown()
23 | }
24 |
25 | func testCompareStrings() {
26 | let A1 = "ABCD"
27 | let B1 = "ACD"
28 | XCTAssertTrue(LCCompareStrings.compareStrings(A1, B: B1))
29 |
30 | let A2 = "ABCD"
31 | let B2 = "AABC"
32 | XCTAssertFalse(LCCompareStrings.compareStrings(A2, B: B2))
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCDepthTreeTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCDepthTreeTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCDepthTreeTest: XCTestCase {
12 | /*
13 | * Given a binary tree as follow:
14 | *
15 | * 1
16 | * / \
17 | * 2 3
18 | * / \
19 | * 4 5
20 | * The maximum depth is 3.
21 | */
22 | func testMaxDepth() {
23 | let node4 = LCTreeNode.init(val: 4)
24 | let node5 = LCTreeNode.init(val: 5)
25 | let node2 = LCTreeNode.init(val: 2, left: node4, right: node5)
26 | let node3 = LCTreeNode.init(val: 3)
27 | let node1 = LCTreeNode.init(val: 1, left: node2, right: node3)
28 |
29 | // Solution 1
30 | XCTAssertTrue(LCDepthTree.maxDepth(node1) == 3)
31 |
32 | // Solution 2
33 | let depthTree = LCDepthTree.init()
34 | XCTAssertTrue(depthTree.maxDepthByTraverse(node1) == 3)
35 |
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCFindMinimumTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFindMinimumTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 |
12 | class LCFindMinimumTest: XCTestCase {
13 |
14 | override func setUp() {
15 | super.setUp()
16 | // Put setup code here. This method is called before the invocation of each test method in the class.
17 | }
18 |
19 | override func tearDown() {
20 | // Put teardown code here. This method is called after the invocation of each test method in the class.
21 | super.tearDown()
22 | }
23 |
24 | // Given [4, 5, 6, 7, 0, 1, 2] return 0
25 | func testFindMin() {
26 | XCTAssertTrue(LCFindMinimum.findMin([4, 5, 6, 7, 0, 1, 2]) == 0)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCFindPeakElementTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFindPeakElementTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCFindPeakElementTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // Given [1, 2, 1, 3, 4, 5, 7, 6]
24 | // Return index 1 (which is number 2) or 6 (which is number 7)
25 | func testFindPeak() {
26 | let nums1 = [1, 2, 1, 3, 4, 5, 7, 6]
27 | XCTAssertTrue(LCFindPeakElement.findPeak(nums1) == 1 || LCFindPeakElement.findPeak(nums1) == 6)
28 |
29 | // let nums2 = [1, 2, 1, 3, 4, 5, 7]
30 | // XCTAssertTrue(LCFindPeakElement.findPeak(nums2) == 1)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCFirstPositionTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFirstPositionTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | // If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
12 | class LCFirstPositionTest: XCTestCase {
13 |
14 | override func setUp() {
15 | super.setUp()
16 | // Put setup code here. This method is called before the invocation of each test method in the class.
17 | }
18 |
19 | override func tearDown() {
20 | // Put teardown code here. This method is called after the invocation of each test method in the class.
21 | super.tearDown()
22 | }
23 |
24 | func testBinarySearch() {
25 | let sortedArray = [1, 2, 3, 3, 4, 5, 10]
26 |
27 | XCTAssertTrue(LCFirstPosition.binarySearch(sortedArray, target: 3) == 2)
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCFlipBitsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCFlipBitsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCFlipBitsTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // Given n = 31 (11111), m = 14 (01110), return 2.
24 | func testBitSwapRequired() {
25 | XCTAssertTrue(LCFlipBits.bitSwapRequired(31, b: 14) == 2)
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCInsertTreeNodeTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCInsertTreeNodeTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 30/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCInsertTreeNodeTest: XCTestCase {
12 |
13 | /** Given binary search tree as follow, after Insert node 6, the tree should be:
14 | *
15 | * 2 2
16 | * / \ / \
17 | * 1 4 --> 1 4
18 | * / / \
19 | * 3 3 6
20 | */
21 | func testInsertNode() {
22 | let newNode = LCTreeNode.init(val: 6)
23 | let treeResult1 = LCInsertTreeNode.insertNode(tree1(), node: newNode)
24 | XCTAssertTrue(LCTreeNodeHelper.compare(treeResult1, node2: expectedTree1()))
25 | }
26 | }
27 |
28 | extension LCInsertTreeNodeTest {
29 | func tree1() -> LCTreeNode {
30 | let node3 = LCTreeNode.init(val: 3)
31 | let node1 = LCTreeNode.init(val: 1, left: node3, right: nil)
32 | let node4 = LCTreeNode.init(val: 4)
33 | let node2 = LCTreeNode.init(val: 2, left: node1, right: node4)
34 |
35 | return node2
36 | }
37 |
38 | func expectedTree1() -> LCTreeNode {
39 | let node3 = LCTreeNode.init(val: 3)
40 | let node6 = LCTreeNode.init(val: 6)
41 | let node1 = LCTreeNode.init(val: 1, left: node3, right: node6)
42 | let node4 = LCTreeNode.init(val: 4)
43 | let node2 = LCTreeNode.init(val: 2, left: node1, right: node4)
44 |
45 | return node2
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCLowestCommonAncestorTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCLowestCommonAncestorTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 12/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCLowestCommonAncestorTest: XCTestCase {
12 | /**
13 | For the following binary tree:
14 |
15 | 4
16 | / \
17 | 3 7
18 | / \
19 | 5 6
20 | LCA(3, 5) = 4
21 |
22 | LCA(5, 6) = 7
23 |
24 | LCA(6, 7) = 7
25 | */
26 | func testLowestCommonAncestor() {
27 | let tree1 = LCTreeNodeHelper.createTreeNode("4,3,7,#,#,5,6")
28 | if let node3 = LCTreeNodeHelper.treeNode(tree1, value: 3), node4 = LCTreeNodeHelper.treeNode(tree1, value: 4), node5 = LCTreeNodeHelper.treeNode(tree1, value: 5), node6 = LCTreeNodeHelper.treeNode(tree1, value: 6), node7 = LCTreeNodeHelper.treeNode(tree1, value: 7) {
29 | XCTAssert(LCLowestCommonAncestor.lowestCommonAncestor(tree1, node1: node3, node2: node5) == node4, "the common of ancestor for 3, 5 is 4")
30 | XCTAssert(LCLowestCommonAncestor.lowestCommonAncestor(tree1, node1: node5, node2: node6) == node7, "the common of ancestor for 5, 6 is 7")
31 | XCTAssert(LCLowestCommonAncestor.lowestCommonAncestor(tree1, node1: node6, node2: node7) == node7, "the common of ancestor for 6, 7 is 7")
32 | }
33 |
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCMergeTwoListsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCMergeTwoListsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCMergeTwoListsTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null.
24 | func testMergeTwoLists() {
25 | let list1 = LCLinkedList.linkedList([1, 3, 8, 11, 15])
26 | let list2 = LCLinkedList.linkedList([2])
27 | let expectedList = LCLinkedList.linkedList([1, 2, 3, 8, 11, 15])
28 |
29 | let mergedList = LCMergeTwoLists.mergeTwoLists(list1, l2: list2)
30 |
31 | XCTAssertTrue(LCLinkedList.compare(expectedList, node2: mergedList))
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCPermutationsIITest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCPermutationsIITest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 14/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCPermutationsIITest: XCTestCase {
12 | func testLCPermutationsII() {
13 | let nums = [1,2,2]
14 | let permutations = LCPermutationsII.init()
15 | let result = permutations.permuteUnique(nums)
16 | let expectedResult = [
17 | [1,2,2],
18 | [2,1,2],
19 | [2,2,1]
20 | ]
21 |
22 | XCTAssert(result.count == 3)
23 |
24 | for expectedList in expectedResult {
25 | var hasList = false
26 | for list in result {
27 | if list == expectedList {
28 | hasList = true
29 | }
30 | }
31 | XCTAssertTrue(hasList)
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCPermutationsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCPermutationsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 9/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCPermutationsTest: XCTestCase {
12 | /**
13 | * For nums = [1,2,3], the permutations are:
14 | *
15 | * [
16 | * [1,2,3],
17 | * [1,3,2],
18 | * [2,1,3],
19 | * [2,3,1],
20 | * [3,1,2],
21 | * [3,2,1]
22 | * ]
23 | *
24 | */
25 |
26 | static let test1 = [1, 2,3]
27 | static let expectedResult1 = [[1, 2,3], [1, 3,2], [2, 1,3], [2, 3,1], [3, 1,2], [3, 2,1]]
28 |
29 | func testPermuteNonRecursion() {
30 | XCTAssertTrue(LCPermutations.permute(LCPermutationsTest.test1) == LCPermutationsTest.expectedResult1)
31 | }
32 |
33 | func testPermute() {
34 | let permutations = LCPermutations()
35 | XCTAssertTrue(permutations.permute(LCPermutationsTest.test1) == LCPermutationsTest.expectedResult1)
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCPlusOneTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCPlusOneTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 18/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCPlusOneTest: XCTestCase {
12 | /**
13 | Given [1,2,3] which represents 123, return [1,2,4].
14 | Given [9,9,9] which represents 999, return [1,0,0,0].
15 | */
16 | func testPlusOne() {
17 | XCTAssert(LCPlusOne.plusOne([1,2,3]) == [1,2,4])
18 | XCTAssert(LCPlusOne.plusOne([9,9,9]) == [1,0,0,0])
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCRemoveDuplicatesFromListTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveDuplicatesFromListTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCRemoveDuplicatesFromListTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // Given 1->1->2, return 1->2.
24 | // Given 1->1->2->3->3, return 1->2->3.
25 | func testDeleteDuplicates() {
26 | let list1 = LCLinkedList.linkedList([1, 1, 2])
27 | let expectList1 = LCLinkedList.linkedList([1, 2])
28 | let listResult1 = LCRemoveDuplicatesFromList.deleteDuplicates(list1)
29 | let list2 = LCLinkedList.linkedList([1, 1, 2, 3, 3])
30 | let expectList2 = LCLinkedList.linkedList([1, 2, 3])
31 | let listResult2 = LCRemoveDuplicatesFromList.deleteDuplicates(list2)
32 |
33 | XCTAssertTrue(LCLinkedList.compare(expectList1, node2: listResult1))
34 | XCTAssertTrue(LCLinkedList.compare(expectList2, node2: listResult2))
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCRemoveDuplicatesTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveDuplicatesTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 27/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCRemoveDuplicatesTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // Given input array A = [1,1,2],
24 | // Your function should return length = 2, and A is now [1,2].
25 | func testRemoveDuplicates() {
26 | XCTAssertTrue(LCRemoveDuplicates.removeDuplicates([1, 1,2]) == 2)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCRemoveElementTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveElementTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 27/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | // Given an array [0,4,4,0,0,2,4,4], value=4
12 | // return 4 and front four elements of the array is [0,0,0,2]
13 | class LCRemoveElementTest: XCTestCase {
14 |
15 | override func setUp() {
16 | super.setUp()
17 | // Put setup code here. This method is called before the invocation of each test method in the class.
18 | }
19 |
20 | override func tearDown() {
21 | // Put teardown code here. This method is called after the invocation of each test method in the class.
22 | super.tearDown()
23 | }
24 |
25 | func testRemoveElement() {
26 | XCTAssertTrue(LCRemoveElement.removeElement([0, 4,4, 0,0, 2,4, 4], elem: 4) == 4)
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCRemoveNodeFromListTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCRemoveNodeFromListTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCRemoveNodeFromListTest: XCTestCase {
12 |
13 | // 1->2->3->4->5->null, 2
14 | var node1: LCLinkedListNode!
15 | //1->2->3->5->null
16 | var node1Result: LCLinkedListNode!
17 |
18 | override func setUp() {
19 | super.setUp()
20 |
21 | node1 = LCLinkedList.linkedList([1, 2, 3, 4, 5])
22 | node1Result = LCLinkedList.linkedList([1, 2, 3, 5])
23 | }
24 |
25 | override func tearDown() {
26 | // Put teardown code here. This method is called after the invocation of each test method in the class.
27 | super.tearDown()
28 | }
29 |
30 | func testRemoveNthFromEnd() {
31 | let node1AfterRemoved = LCRemoveNodeFromList.removeNthFromEnd(node1, n: 2)
32 | XCTAssertTrue(LCLinkedList.compare(node1AfterRemoved!, node2: node1Result))
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCReverseIntegerTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCReverseIntegerTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 17/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCReverseIntegerTest: XCTestCase {
12 | func testReverseInteger() {
13 | XCTAssert(LCReverseInteger.reverseInteger(123) == 321)
14 | XCTAssert(LCReverseInteger.reverseInteger(-123) == -321)
15 | XCTAssert(LCReverseInteger.reverseInteger(-1) == -1)
16 | XCTAssert(LCReverseInteger.reverseInteger(0) == 0)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCReverseLinkedListTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCReverseLinkedListTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 29/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCReverseLinkedListTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // For linked list 1->2->3, the reversed linked list is 3->2->1
24 | func testReverse() {
25 | let list = LCLinkedList.linkedList([1, 2, 3])
26 | let expectList = LCLinkedList.linkedList([3, 2, 1])
27 | let listResult = LCReverseLinkedList.reverse(list)
28 |
29 | XCTAssertTrue(LCLinkedList.compare(expectList, node2: listResult))
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCSearch2DMatrixTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCSearch2DMatrixTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | /* Consider the following matrix:
12 | [
13 | [1, 3, 5, 7],
14 | [10, 11, 16, 20],
15 | [23, 30, 34, 50]
16 | ]
17 | Given target = 3, return true.
18 | */
19 | class LCSearch2DMatrixTest: XCTestCase {
20 |
21 | override func setUp() {
22 | super.setUp()
23 | // Put setup code here. This method is called before the invocation of each test method in the class.
24 | }
25 |
26 | override func tearDown() {
27 | // Put teardown code here. This method is called after the invocation of each test method in the class.
28 | super.tearDown()
29 | }
30 |
31 |
32 | func testSearchMatrix() {
33 | let matrix = [
34 | [1, 3, 5, 7],
35 | [10, 11, 16, 20],
36 | [23, 30, 34, 50]
37 | ]
38 |
39 | XCTAssertTrue(LCSearch2DMatrix.searchMatrix(matrix, target: 3))
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCStrStrTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCStrStrTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 26/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | // If source = "source" and target = "target", return -1.
12 | // If source = "abcdabcdefg" and target = "bcd", return 1.
13 |
14 | class LCStrStrTest: XCTestCase {
15 |
16 | override func setUp() {
17 | super.setUp()
18 | // Put setup code here. This method is called before the invocation of each test method in the class.
19 | }
20 |
21 | override func tearDown() {
22 | // Put teardown code here. This method is called after the invocation of each test method in the class.
23 | super.tearDown()
24 | }
25 |
26 | func testStrStr() {
27 | let source1 = "source"
28 | let target1 = "target"
29 | XCTAssertTrue(LCStrStr.strStr(source1, target: target1) == -1)
30 |
31 | let source2 = "abcdabcdefg"
32 | let target2 = "bcd"
33 | XCTAssertTrue(LCStrStr.strStr(source2, target: target2) == 1)
34 | }
35 |
36 |
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCSubarraySumTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCSubarraySumTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 27/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | // Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
12 | class LCSubarraySumTest: XCTestCase {
13 |
14 | override func setUp() {
15 | super.setUp()
16 | // Put setup code here. This method is called before the invocation of each test method in the class.
17 | }
18 |
19 | override func tearDown() {
20 | // Put teardown code here. This method is called after the invocation of each test method in the class.
21 | super.tearDown()
22 | }
23 |
24 | func testSubarraySum() {
25 | let result = LCSubarraySum.subarraySum([-3, 1, 2, -3, 4])
26 | XCTAssertTrue(result == [0, 2] || result == [1, 3])
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCSubsetsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCSubsetsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 11/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCSubsetsTest: XCTestCase {
12 | /**
13 | If S = [1,2,3], a solution is:
14 |
15 | [
16 | [3],
17 | [1],
18 | [2],
19 | [1,2,3],
20 | [1,3],
21 | [2,3],
22 | [1,2],
23 | []
24 | ]
25 | */
26 | func testSubsets() {
27 | let input1 = [1, 2,3]
28 | let expectedOutput1 = [
29 | [3],
30 | [1],
31 | [2],
32 | [1, 2, 3],
33 | [1, 3],
34 | [2, 3],
35 | [1, 2],
36 | []
37 | ]
38 | let output1 = LCSubsets.subsets(input1)
39 |
40 | XCTAssertTrue(expectedOutput1.count == output1.count)
41 |
42 | for array in expectedOutput1 {
43 | XCTAssertTrue(output1.contains {
44 | $0 == array
45 | })
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCTreeInOrderTraverseTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeInOrderTraverseTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 10/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCTreeInOrderTraverseTest: XCTestCase {
12 | /**
13 | * Given:
14 | *
15 | * 1
16 | * / \
17 | * 2 3
18 | * / \
19 | * 4 5
20 | *
21 | * return [4,2,5,1,3].
22 | */
23 | func testEnumerateTreeNode() {
24 | let test1 = "1,2,3,4,5,#,#"
25 | let expectedTest1 = [4, 2,5, 1,3]
26 | let node1 = LCTreeNodeHelper.createTreeNode(test1)
27 | var index = 0
28 |
29 | LCTreeInOrderTraverse.enumerateTreeNode(node1) { (currentValue) in
30 | XCTAssertTrue(currentValue == expectedTest1[index])
31 | index += 1
32 | }
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCTreeLevelTraversalTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeLevelTraversalTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 5/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCTreeLevelTraversalTest: XCTestCase {
12 | /**
13 | * Given binary tree {3,9,20,#,#,15,7},
14 | *
15 | * 3
16 | * / \
17 | * 9 20
18 | * / \
19 | * 15 7
20 | *
21 | *
22 | * return its level order traversal as:
23 | *
24 | * [
25 | * [3],
26 | * [9,20],
27 | * [15,7]
28 | * ]
29 | */
30 | func testLevelOrderBFS() {
31 | let treeResult1 = LCTreeLevelTraversal.levelOrder(tree1(), methods: TraversalType.BFS)
32 | XCTAssertTrue(treeResult1 == expectedTree1())
33 | }
34 |
35 | func testLevelOrderDFS() {
36 | let treeResult1 = LCTreeLevelTraversal.levelOrder(tree1(), methods: TraversalType.DFS)
37 | XCTAssertTrue(treeResult1 == expectedTree1())
38 | }
39 |
40 | func testLevelOrderBFSWithTwoQueues() {
41 | let treeResult1 = LCTreeLevelTraversal.levelOrder(tree1(), methods: TraversalType.BFSWithTwoQueues)
42 | XCTAssertTrue(treeResult1 == expectedTree1())
43 | }
44 |
45 | func testLevelOrderBFSQueueWithDummyNode() {
46 | let treeResult1 = LCTreeLevelTraversal.levelOrder(tree1(), methods: TraversalType.BFSQueueWithDummyNode)
47 | XCTAssertTrue(treeResult1 == expectedTree1())
48 | }
49 |
50 | func tree1() -> LCTreeNode {
51 | return LCTreeNodeHelper.createTreeNode("3,9,20,#,#,15,7")
52 | }
53 |
54 | func expectedTree1() -> [[Int]] {
55 | return [[3], [9, 20], [15, 7]]
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCTreeNodeHelperTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreeNodeHelperTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 3/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCTreeNodeHelperTest: XCTestCase {
12 | /**
13 | *
14 | * 1
15 | * / \
16 | * 2 3
17 | * / \
18 | * 4 5
19 | */
20 | func testCreateTreeNode() {
21 | let node4 = LCTreeNode.init(val: 4)
22 | let node5 = LCTreeNode.init(val: 5)
23 | let node2 = LCTreeNode.init(val: 2, left: node4, right: node5)
24 | let node3 = LCTreeNode.init(val: 3)
25 | let node1 = LCTreeNode.init(val: 1, left: node2, right: node3)
26 |
27 | let node = LCTreeNodeHelper.createTreeNode("1,2,3,4,5,#,#")
28 |
29 | XCTAssertTrue(LCTreeNodeHelper.compare(node1, node2: node))
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCTreePreOrderTraverseTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTreePreOrderTraverseTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 4/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCTreePreOrderTraverseTest: XCTestCase {
12 | /**
13 | * Given:
14 | *
15 | * 1
16 | * / \
17 | * 2 3
18 | * / \
19 | * 4 5
20 | *
21 | * return [1,2,4,5,3].
22 | */
23 | func testEnumerateTreeNode() {
24 | let test1 = "1,2,3,4,5,#,#"
25 | let expectedTest1 = [1, 2, 4, 5, 3]
26 | let node1 = LCTreeNodeHelper.createTreeNode(test1)
27 | var index = 0
28 |
29 | LCTreePreOrderTraverse.enumerateTreeNode(node1) { (currentValue) in
30 | XCTAssertTrue(currentValue == expectedTest1[index])
31 | index += 1
32 | }
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCTwoSumTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCTwoSumTest.swift
3 | // InterviewInSwift
4 | //
5 | // Created by Jingwei Huang on 15/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCTwoSumTest: XCTestCase {
12 | /**
13 | Example
14 | numbers=[2, 7, 11, 15], target=9
15 |
16 | return [0, 1]
17 | */
18 | func testTwoSum() {
19 | XCTAssert(LCTwoSum.twoSum([2, 7, 11, 15], target: 9) == [0, 1])
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCUniquePathsTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCUniquePathsTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 28/06/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCUniquePathsTest: XCTestCase {
12 |
13 | override func setUp() {
14 | super.setUp()
15 | // Put setup code here. This method is called before the invocation of each test method in the class.
16 | }
17 |
18 | override func tearDown() {
19 | // Put teardown code here. This method is called after the invocation of each test method in the class.
20 | super.tearDown()
21 | }
22 |
23 | // 3, 7 -> 28
24 | // 8, 8 -> 3432
25 | func testUniquePaths() {
26 | XCTAssertTrue(LCUniquePaths.uniquePaths(3, n: 7) == 28)
27 | XCTAssertTrue(LCUniquePaths.uniquePaths(8, n: 8) == 3432)
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewInSwiftTests/LintCode/LCWordLadderTest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LCWordLadderTest.swift
3 | // swift-lintcode
4 | //
5 | // Created by Jingwei Huang on 7/07/2016.
6 | // Copyright © 2016 Core Apps Pty Ltd. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class LCWordLadderTest: XCTestCase {
12 | /**
13 | * Given:
14 | * start = "hit"
15 | * end = "cog"
16 | * dict = ["hot","dot","dog","lot","log"]
17 | * As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
18 | * return its length 5.
19 | *
20 | */
21 | func testLadderLength() {
22 | let wordLadder = LCWordLadder()
23 | var set = Set(["hot", "dot", "dog", "lot", "log"])
24 | XCTAssertTrue(wordLadder.ladderLength("hit", end: "cog", dict: &set) == 5)
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #Crack Interview In Swift#
2 |
3 | [](https://codebeat.co/projects/github-com-fg0815-swift-lintcode)
4 | [](https://travis-ci.org/fg0815/Interview-In-Swift)
5 | 
6 | [](https://codecov.io/gh/fg0815/Interview-In-Swift)
7 | [](http://waffle.io/fg0815/Interview-In-Swift)
8 |
9 | The project is helping developers who are cracking algorithm questions by using Swift. The questions are from [LintCode](http://www.lintcode.com), [LeetCode](http://www.leetcode.com), and [Hackerrank](https://www.hackerrank.com). Also This project is targeting to interview questions from Facebook, Google, Linkedin, Amazon, Apple, etc, which are from [Glassdoor](http://glassdoor.com.au) and [Career Cup](http://careercup.com).
10 |
11 | The project is still under development
12 |
13 | ##How to use##
14 | - The project was built by Xcode 7.3 with Swift 2.2.x
15 | - The project only runs via tests (command + U) with any iOS simulator as a target
16 |
17 | ##Solutions##
18 | ###LeetCode###
19 | [2. Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)
20 | [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/)
21 | [8. String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)
22 | [9. Palindrome Number](https://leetcode.com/problems/palindrome-number/)
23 | [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/)
24 | [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
25 | [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
26 | [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)
27 | [26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)
28 | [27. Remove Element](https://leetcode.com/problems/remove-element/)
29 | [28. Implement strStr()](https://leetcode.com/problems/implement-strstr/)
30 | [46. Permutations](https://leetcode.com/problems/permutations/)
31 | [47. Permutations II](https://leetcode.com/problems/permutations-ii/)
32 | [50. Pow(x, n)](https://leetcode.com/problems/powx-n/)
33 | [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/)
34 | [62. Unique Paths](https://leetcode.com/problems/unique-paths/)
35 | [66. Plus One](https://leetcode.com/problems/plus-one/)
36 | [78. Subsets](https://leetcode.com/problems/subsets/)
37 | [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)
38 | [94. Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)
39 | [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
40 | [100. Same Tree](https://leetcode.com/problems/same-tree/)
41 | [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
42 | [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
43 | [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)
44 | [127. Word Ladder](https://leetcode.com/problems/word-ladder/)
45 | [144. Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)
46 | [153. Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
47 | [162. Find Peak Element](https://leetcode.com/problems/find-peak-element/)
48 | [205. Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)
49 | [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)
50 | [231. Power of Two](https://leetcode.com/problems/power-of-two/)
51 | [235. Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
52 | [244. Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/)
53 | [254. Factor Combinations](https://leetcode.com/problems/factor-combinations/)
54 | [367. Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)
55 |
56 | ###LintCode###
57 | ####Integer####
58 | [Reverse Integer](http://www.lintcode.com/en/problem/reverse-integer/)
59 |
60 | ####Binary Search####
61 | [Find Minimum in Rotated Sorted Array](http://www.lintcode.com/en/problem/find-minimum-in-rotated-sorted-array/)
62 | [Find Peak Element](http://www.lintcode.com/en/problem/find-peak-element/)
63 | [First Position of Target](http://www.lintcode.com/en/problem/first-position-of-target/)
64 | [Search a 2D Matrix](http://www.lintcode.com/en/problem/search-a-2d-matrix/)
65 |
66 | ####Binary Tree####
67 | [Balanced Binary Tree](http://www.lintcode.com/en/problem/balanced-binary-tree/)
68 | [Search Range in Binary Search Tree](http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/)
69 | [Validate Binary Search Tree](http://www.lintcode.com/en/problem/validate-binary-search-tree/)
70 | [Maximum Depth of Binary Tree](http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/)
71 | [Insert Node in a Binary Search Tree](http://www.lintcode.com/en/problem/insert-node-in-a-binary-search-tree/)
72 | [Binary Tree Inorder Traversal](http://www.lintcode.com/en/problem/binary-tree-inorder-traversal/)
73 | [Binary Tree Level Order Traversal](http://www.lintcode.com/en/problem/binary-tree-level-order-traversal/)
74 | [Binary Tree Preorder Traversal](http://www.lintcode.com/en/problem/binary-tree-preorder-traversal)
75 | [Lowest Common Ancestor](http://www.lintcode.com/en/problem/lowest-common-ancestor/)
76 |
77 | ####Integer Array####
78 | [Remove Duplicates from Sorted Array](http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-array/)
79 | [Remove Element](http://www.lintcode.com/en/problem/remove-element/)
80 | [Subarray Sum](http://www.lintcode.com/en/problem/subarray-sum/)
81 | [Two Sum](http://www.lintcode.com/en/problem/two-sum/)
82 | [Plus One](http://www.lintcode.com/en/problem/plus-one/)
83 | []()
84 |
85 | ####Linked List####
86 | [Add Two Numbers](http://www.lintcode.com/en/problem/add-two-numbers/)
87 | [Merge Two Sorted Lists](http://www.lintcode.com/en/problem/merge-two-sorted-lists/)
88 | [Remove Duplicates from Sorted List](http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-list/)
89 | [Remove Nth Node From End of List](http://www.lintcode.com/en/problem/remove-nth-node-from-end-of-list/)
90 | [Reverse Linked List](http://www.lintcode.com/en/problem/reverse-linked-list/)
91 |
92 | ####Math & Bit Manipulation####
93 | [O(1) Check Power of 2](http://www.lintcode.com/en/problem/o1-check-power-of-2/)
94 | [Flip bits](http://www.lintcode.com/en/problem/flip-bits/)
95 | [Unique Paths](http://www.lintcode.com/en/problem/unique-paths/)
96 |
97 | ####Search & Recursion####
98 | [Permutations](http://www.lintcode.com/en/problem/permutations/)
99 | [Subsets](http://www.lintcode.com/en/problem/subsets/)
100 | [Word Ladder](http://www.lintcode.com/en/problem/word-ladder/)
101 | [Permutations II](http://www.lintcode.com/en/problem/permutations-ii/)
102 |
103 | ####String####
104 | [Two Strings Are Anagrams](http://www.lintcode.com/en/problem/two-strings-are-anagrams/)
105 | [Compare Strings](http://www.lintcode.com/en/problem/compare-strings/)
106 | [strStr](http://www.lintcode.com/en/problem/strstr/)
107 |
108 |
109 |
110 |
111 |
112 |
--------------------------------------------------------------------------------