Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
53 changes: 53 additions & 0 deletions Array/KidsWithCandies.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*

Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.

For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.



Example 1:

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation:
Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids.
Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
Kid 3 has 5 candies and this is already the greatest number of candies among the kids.
Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies.
Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
Example 2:

Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy.
Example 3:

Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]


Constraints:

2 <= candies.length <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50


*/



func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] {

var mostCandies = 0

for value in candies {
if value > mostCandies {
mostCandies = value
}
}

return candies.map {($0 + extraCandies) >= mostCandies}

}
File renamed without changes.
80 changes: 80 additions & 0 deletions Array/NumberOfGoodPairs.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*

1512. Number of Good Pairs

Given an array of integers nums.

A pair (i,j) is called good if nums[i] == nums[j] and i < j.

Return the number of good pairs.



Example 1:

Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:

Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:

Input: nums = [1,2,3]
Output: 0


Constraints:

1 <= nums.length <= 100
1 <= nums[i] <= 100


*/



/* Solution 1: */
/* Brute Force: */
// Complexity O(n^2)
func numIdenticalPairs(_ nums: [Int]) -> Int {

var returnValue = 0

(0..<(nums.count - 1)).forEach { (value) in
((value + 1)..<nums.count).forEach { (inValue) in
if nums[value] == nums[inValue] {
returnValue += 1
}
}
}

return returnValue
}

/* Solution 2: */
/* Dictionary: */
/* Complexity: O(n) */
func numIdenticalPairs(_ nums: [Int]) -> Int {

var dict = [Int: Int]()

nums.forEach { // O(n)
if let value = dict[$0] {
dict[$0] = value + 1
} else {
dict[$0] = 1
}
}

var returnValue = 0

dict.values.forEach { // O(n)
returnValue += $0 * ($0 - 1) / 2
}

return returnValue

}
53 changes: 51 additions & 2 deletions Array/ShuffleArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ nums.length == 2n

*/

// Solution 1


func shuffle(_ nums: [Int], _ n: Int) -> [Int] {
Expand All @@ -50,7 +51,55 @@ func shuffle(_ nums: [Int], _ n: Int) -> [Int] {
Time Complexity: O(n)
Space Complexity: O(n)

Further scope: This algorithm can be solved with space O(1)
Needs further analysis.
*/

// Solution 2

/*

Explanation inspired from https://leetcode.com/problems/shuffle-the-array/discuss/675956/In-Place-O(n)-Time-O(1)-Space-With-Explanation-and-Analysis

*/

func shuffle(_ array: inout [Int], _ n: Int) -> [Int] {

// left shift and right shift of 10 was chosen because number in algo has been constrained to 10^3 which means
// this can be maximum of 1000 and that also means under 1024 decimal number and can be represented with 10 bits.

(0..<n).forEach {
let rightNumber = (array[$0] << 10) | array[$0 + n] // 10 bit left movement for number 1 and bitwise addition of 2nd
array[$0 + n] = rightNumber // store both numbers in 2nd part of array through bitwise representation
}


// Suppose only 4 bits are allowed..


// Storing 9 and 12 in bit representation
/// 12 -> 1100 << 4 -> 11000000 12 is 1100 in bits. Left shift it by 4 to get 11000000
/// 9 | 11000000 -> 11001001 now perform bitwise OR with 9 (1001) to get 11001001

// Now, 12 and 9 are inside 11001001 1100 (12) 1001 (9)

// To get them back:

/// 11001001 & 00001111 -> 00001001 -> 9 To get 9 back from 11001001, perform bitwise and with 1111 -> 11001001 & 00001111 -> 00001001 -> 9
/// 11001001 >> 4 -> 1100 -> 12 To get 12 back from 11001001, right shift it back by 4 ... 11001001 >> 4 -> 00001100 -> 12

var i = 0

(n..<(2 * n)).forEach {
array[i] = (array[$0]) >> 10 // Get number on left with right shift
array[i + 1] = array[$0] & 1023 // Get number of right with nullifying left number and getting only right digit
i += 2
}

return array
}

/*

Time Complexity: O(n)
Space Complexity: O(1)

*/
27 changes: 20 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
# What exactly is an algorithm?
*(To skip reading the introduction, you can scroll down to "Algorithms-With-Swift" section.)*

An algorithm is a procedure that transforms/converts an input into an output.

In an algorithm, a **series of computations** are applied on an input to get an output. We can call this sequential series of computations a **procedure**, and this procedure is what we call an **algorithm**.

# Algorithms-With-Swift
Writing this project for reference, fun and learning purposes. Have started with simple algorithms, will try to cover more as we go on this journey
Writing this project for learning purposes. We have started with simple algorithms, and we will try to cover more as we go further.

## Common Algorithms
We will be solving algorithm problem statements using Swift Programming Language to begin with.

## Algorithms

### Array

- [Reverse an Array](Array/ReverseArray.swift)
- [Two Sum Problem](Array/TwoSumProblem.swift)
- [Non-decreasing Array](Array/LeetCode665.swift)
- [Non-decreasing Array](Array/NonDecreasingArrayWithOneChange.swift)
- [Find Third Maximum in Array](Array/FindThirdMax.swift)
- [Triplet Sum problem](Array/find_triplet.swift)
- [First Non Repetitive number in array](Array/first_non_repetative_number.swift)
- [Triplet Sum problem](Array/FindTriplet.swift)
- [First Non Repetitive number in array](Array/FirstNonRepetitiveNumber.swift)
- [Data Source Array](Array/DataSourceArray.swift)
- [Array Running Sum](Array/RunningSum.swift)
- [Shortest Unsorted Continuous Subarray](Array/ContinuousUnsortedSubarray.swift)
- [Rotate Array](Array/RotateArray.swift)
- [Reverse Digits](Array/ReverseDigits.swift)
- [Sum of Integer digits](Array/SumOfDigits.swift)
- [Shuffle Array](Array/ShuffleArray.swift)
- [Find Duplicate - Floyed - Tortoie and Hare algo ](Array/floyedTortoieAndHareDuplicateDetection.swift)
- [Longest SubArray by Sum](Array/findLongestSubArrayBySum.swift)
- [Find Duplicate - Floyed - Tortoie and Hare algo ](Array/FloyedTortoieAndHareDuplicateDetection.swift)
- [Longest SubArray by Sum](Array/LongestSubarrayBySum.swift)
- [Kids With the Greatest Number of Candies](Array/KidsWithCandies.swift)
- [Number Of Good Pairs](Array/NumberOfGoodPairs.swift)


### Strings

Expand All @@ -28,6 +40,7 @@ Writing this project for reference, fun and learning purposes. Have started with
- [Create Unique String](String/Create_Unique_string.swift)
- [Find Anagram](String/find_anagram.swift)
- [Unique String](String/Unique_string.swift)
- [Buddy Strings Leetcode](String/BuddyStrings.swift)

### Sort

Expand Down
91 changes: 91 additions & 0 deletions String/BuddyStrings.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*

Leetcode: 859. Buddy Strings

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.



Example 1:

Input: A = "ab", B = "ba"
Output: true
Example 2:

Input: A = "ab", B = "ab"
Output: false
Example 3:

Input: A = "aa", B = "aa"
Output: true
Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:

Input: A = "", B = "aa"
Output: false


Constraints:

0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.


*/


func buddyStrings(_ A: String, _ B: String) -> Bool {

if A.count != B.count {return false}

var result: Bool = false

if A == B { // If two strings are equal
var repeatChars = [Character]() // Then check if any character is repeated in string

outer: for value in (0..<A.count) {

let aValue = A[A.index(A.startIndex, offsetBy: value)]

if repeatChars.contains(aValue) {
result = true // If so, then that means that this condition is true and
break outer // A and B are buddies
} else { // For example, aaac and aaac are buddies because with at most one change
repeatChars.append(aValue) // will keep the strings same. i.e. if a and a is swapped in A or B
}
}

} else { /// If A and B are not equal

var repeatChars: (Character, Character)?

outer: for value in (0..<A.count) { // Loop through each character index and check the index where two strings are not equal

let aValue = A[A.index(A.startIndex, offsetBy: value)]
let bValue = B[B.index(B.startIndex, offsetBy: value)]

if aValue != bValue { /// Found a point where Character in 'A' is not equal to that in 'B'
if repeatChars == nil {
repeatChars = (aValue, bValue) // This is the first time we have found an inequality, save this in a tuple
} else {
result = (repeatChars!.0 == bValue) && (repeatChars!.1 == aValue) // This is the second time we have found an inequality, compare if point of inequality equals to what we have stored in tuple before
if !result {break outer} // If the two points are inequal, it means that at least a single swap won't make them equal.
}
}
}

}

return result
}


/*

Solution: https://leetcode.com/problems/buddy-strings/solution/

*/