Common Array Algorithm Interview Questions in Swift || iOS - Part-2


Interview Questions and Coding Challenges

Question 1: RemoveDuplicates item in swift

If you want to remove duplicate elements from an array in Swift and obtain a new array with unique elements, you can do so using Swift's Set data structure. Here's how you can remove duplicates from an array in Swift:

let arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]

let set = Set(arrayWithDuplicates) // Convert the array to a Set to remove duplicates

let arrayWithoutDuplicates = Array(set) // Convert the Set back to an array

print(arrayWithoutDuplicates) // This will print: [5, 2, 3, 1, 4]

In this example, we first convert the array with duplicates into a Set. Sets automatically remove duplicate elements. Then, we convert the Set back into an array to obtain an array with unique elements.

Keep in mind that the order of elements may not be preserved when using this approach because Sets do not guarantee element order. 

If you need to preserve the order of elements while removing duplicates, you can use the following approach:

func removeDuplicates<T: Equatable>(_ array: [T]) -> [T] {
    var result: [T] = []
    
    for element in array {
        if !result.contains(element) {
            result.append(element)
        }
    }
    
    return result
}

let arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]
let arrayWithoutDuplicates = removeDuplicates(arrayWithDuplicates)

print(arrayWithoutDuplicates) // This will print: [1, 2, 3, 4, 5]

In this alternative approach, we iterate through the original array, checking if each element is already present in the result array. If not, we add it to the result array. This way, we maintain the order of elements while removing duplicates.

Question 2: Two Sum

Example:

Input: nums = [2, 7, 11, 15], target = 9

Output: [0, 1] (because nums[0] + nums[1] == 9)

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var numToIndex = [Int: Int]()
    
    for (index, num) in nums.enumerated() {
        let complement = target - num
        
        if let complementIndex = numToIndex[complement] {
            return [complementIndex, index]
        }
        
        numToIndex[num] = index
    }
    
    fatalError("No valid solution found")
}

// Example usage:
let nums = [2, 7, 11, 15]
let target = 9
let result = twoSum(nums, target)
print(result)  // This will print [0, 1]

In this solution, we use a dictionary (numToIndex) to store the elements we have seen so far along with their indices. We iterate through the nums array, calculate the complement (the value we need to reach the target), and check if the complement exists in our dictionary. If it does, we return the indices of the two elements that add up to the target.

This solution has a time complexity of O(n) because it only requires a single pass through the array, and it has a space complexity of O(n) due to the dictionary used to store elements and their indices.

Question 3: Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example:

Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3

Output: [5, 6, 7, 1, 2, 3, 4]

func rotate(_ nums: inout [Int], _ k: Int) {
    let n = nums.count
    let actualK = k % n
    
    reverse(&nums, 0, n - 1)
    reverse(&nums, 0, actualK - 1)
    reverse(&nums, actualK, n - 1)
}

func reverse(_ nums: inout [Int], _ start: Int, _ end: Int) {
    var start = start
    var end = end
    
    while start < end {
        nums.swapAt(start, end)
        start += 1
        end -= 1
    }
}

// Example usage:
var nums = [1, 2, 3, 4, 5, 6, 7]
let k = 3
rotate(&nums, k)
print(nums) // This will print [5, 6, 7, 1, 2, 3, 4]

In this solution, we first reverse the entire array. Then, we reverse the first k elements, and finally, we reverse the remaining elements. This simulates rotating the array to the right by k steps.

The rotate function takes the array nums and the number of steps to rotate k. The reverse function is a helper function that reverses a portion of the array.

This solution has a time complexity of O(n) and a space complexity of O(1).

Question 4: Find the Missing Number in an Array

You are given an array containing n distinct numbers taken from 0, 1, 2, ..., n, except for one missing number. Find that missing number.

Example:

Input: [3, 0, 1]

Output: 2

func findMissingNumber(_ nums: [Int]) -> Int {
    let expectedSum = (nums.count * (nums.count + 1)) / 2
    let actualSum = nums.reduce(0, +)
    
    return expectedSum - actualSum
}

// Example usage:
let nums = [3, 0, 1]
let missingNumber = findMissingNumber(nums)
print(missingNumber) // This will print 2

In this solution, we calculate the expected sum of all numbers from 0 to n using the formula (n * (n + 1)) / 2. Then, we find the actual sum of the numbers in the given array using the reduce function. The missing number is the difference between the expected sum and the actual sum.

This solution has a time complexity of O(n) because it iterates through the array once, and it has a space complexity of O(1) because it uses a constant amount of additional space regardless of the size of the input array.

Question 5: Maximum Subarray Sum

Given an array of integers, find the contiguous subarray (containing at least one number) that has the largest sum and return its sum.

Example:

Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Output: 6 (The contiguous subarray [4, -1, 2, 1] has the largest sum of 6.)

func maxSubArray(_ nums: [Int]) -> Int {
    var maxSum = nums[0] // Initialize maxSum to the first element of the array
    var currentSum = nums[0] // Initialize currentSum to the first element of the array
    
    for i in 1..<nums.count {
        // Calculate the current maximum sum ending at index i
        currentSum = max(nums[i], currentSum + nums[i])
        
        // Update the global maximum sum if needed
        maxSum = max(maxSum, currentSum)
    }
    
    return maxSum
}

// Example usage:
let nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
let result = maxSubArray(nums)
print(result) // This will print 6

In this solution, we use a dynamic programming approach to find the maximum subarray sum. We maintain two variables: maxSum to store the global maximum sum encountered so far, and currentSum to store the maximum sum ending at the current index. We iterate through the array, updating currentSum to either the current element or the sum of the current element and currentSum, whichever is greater. At each step, we also update maxSum to store the maximum of the current maxSum and currentSum. This way, we find the maximum subarray sum efficiently.

This solution has a time complexity of O(n) because it iterates through the array once, and a space complexity of O(1) because it uses only two variables to store the sums.

Question 6: Reverse an Array in Place

Write a function to reverse an array in-place. Modify the original array, without creating a new one.

Example:

Input: [1, 2, 3, 4, 5]

Output: [5, 4, 3, 2, 1]

func reverseArrayInPlace(_ nums: inout [Int]) {
    var left = 0
    var right = nums.count - 1
    
    while left < right {
        // Swap the elements at left and right indices
        let temp = nums[left]
        nums[left] = nums[right]
        nums[right] = temp
        
        // Move the pointers towards the center
        left += 1
        right -= 1
    }
}

// Example usage:
var nums = [1, 2, 3, 4, 5]
reverseArrayInPlace(&nums)
print(nums) // This will print [5, 4, 3, 2, 1]

This solution has a time complexity of O(n) and a space complexity of O(1) since it reverses the array in-place without using additional space proportional to the input size.

Question 7: Neither Minimum nor Maximum

Input: nums = [3,2,1,4]
Output: 2
Find the minimum and maximum values in the array.
Iterate through the array, adding elements to a new array if they are neither the minimum nor the maximum.

func findNeitherMinNorMax(_ nums: [Int]) -> [Int] {
    if nums.count < 3 {
        return [] // Not enough elements in the array
    }
    
    let minVal = nums.min() ?? Int.max // Find the minimum value (default to Int.max if the array is empty)
    let maxVal = nums.max() ?? Int.min // Find the maximum value (default to Int.min if the array is empty)
    
    var result = [Int]()
    
    for num in nums {
        if num != minVal && num != maxVal {
            result.append(num)
        }
    }
    
    return result
}

// Example usage:
let nums = [3, 1, 5, 2, 4]
let result = findNeitherMinNorMax(nums)
print(result) // This will print [3, 2]

We find the minimum and maximum values in the input array nums using the min() and max() functions. We use Int.max and Int.min as default values in case the array is empty.

We iterate through the array and add elements to the result array if they are neither the minimum nor the maximum values.

Finally, we return the result array containing the elements that are neither the minimum nor the maximum.

Question 8: Find the second-largest number in an unsorted array?

func secandLarget(arr:[Int]) -> Int {
    var firstL = arr[0]
    var secondL = arr[0]
    for item in arr{
        if firstL < item{
            firstL = item
        }
    }
    for j in arr{
        if j != firstL && secondL < j{
            secondL = j
        }
    }
    return secondL
}

Question 9: Third Largest Number in an Array

func thirdLarget(arr:[Int]) -> Int {
    var array = arr
    var temp = 0
    
    for i in 0..<array.count{
        for j in i+1..<array.count{
            if array[i] > array[j]{
                temp = array[i]
                array[i] = array[j]
                array[j] = temp
            }
        }
    }
//    return array[array.count - 2] //secand element - 7
    return array[array.count - 3] //6
}
//print(thirdLarget(arr: TempArray))

Question 10: MinMAxValue in an Array

func minMAxValue(arr:[Int]) -> (minValue:Int,maxValue:Int){
    var minValue = arr[0]
    var maxValue = arr[0]
    
    for index in 1..<arr.count{
        if arr[index] < minValue{
            minValue = arr[index]
        }else if arr[index] > maxValue{
            maxValue = arr[index]
        }
    }
   return (minValue,maxValue)
}

Question 11: Search an Element in an Array

func isElement(arr:[Int],findItem:Int) -> Bool {
    for item in arr{
        if item == findItem{
            return true
        }
    }
    return false
// OR-- retrurn arr.contains(findItem)
}

Thanks for reading and happy coding. 🙂


Post a Comment

0 Comments