Search Your Question

Showing posts with label Programming Test. Show all posts
Showing posts with label Programming Test. Show all posts

Write a function which returns the minimum, maximum, average banking transaction amount. How you can optimise those functions for execution time and in terms of memory allocation?

 Answer: 

Using higher-order function:

import Foundation


// Function to calculate min, max, and average transaction amounts

func calculateTransactionStats(transactions: [Double]) -> (min: Double?, max: Double?, average: Double?) {
    guard !transactions.isEmpty else {
        return (nil, nil, nil) // Handle empty array case
    }
    
    let minTransaction = transactions.min()
    let maxTransaction = transactions.max()
    let averageTransaction = transactions.reduce(0, +) / Double(transactions.count)
    
    return (minTransaction, maxTransaction, averageTransaction)
}

Without using higher-order function (optimised code in terms of memory allocation and execution time): 


import Foundation

// Function to calculate min, max, and average without using higher-order functions
func calculateTransactionStats(transactions: [Double]) -> (min: Double?, max: Double?, average: Double?) {
    guard !transactions.isEmpty else {
        return (nil, nil, nil) // Handle empty array case
    }

    var minTransaction = transactions[0]
    var maxTransaction = transactions[0]
    var total = 0.0
    
    for transaction in transactions {
        if transaction < minTransaction {
            minTransaction = transaction
        }
        if transaction > maxTransaction {
            maxTransaction = transaction
        }
        total += transaction
    }
    
    let averageTransaction = total / Double(transactions.count)
    return (minTransaction, maxTransaction, averageTransaction)
}


// Example usage
let transactions = [1200.5, 450.0, 2300.0, 560.0, 890.75]
let stats = calculateTransactionStats(transactions: transactions)
print("Minimum Transaction: \(stats.min ?? 0)")
print("Maximum Transaction: \(stats.max ?? 0)")
print("Average Transaction: \(stats.average ?? 0)")

Optimisations Explained:

  1. Single Loop:

    • In the original implementation, no redundant loops are present since everything is already computed in a single loop. This is efficient and does not require optimization.
  2. Avoid Extra Memory Allocation:

    • We are only using three variables (minTransactionmaxTransaction, and total) to store intermediate values.
    • No extra arrays or data structures are created during computation.
  3. Direct Access:

    • We directly access elements of the array using a for loop without calling methods like min()max(), or reduce(). This avoids any extra function calls or higher-order function overhead.
  4. Efficient Guard Clause:

    • The guard statement ensures the function exits early if the input array is empty, avoiding unnecessary computations.

Additional Suggestions for Large Datasets:

  1. Use Parallel Processing for Large Datasets:

    • If the dataset is very large, you can divide the array into chunks and process each chunk in parallel using concurrency (e.g., GCD or Swift's async/await) to compute partial min, max, and sum. Combine these partial results in the end.
    • However, note that this may only be beneficial when the array size is extremely large, as parallelism introduces its own overhead.
  2. Precision Control:

    • For very large datasets or high precision requirements, consider using floating-point types like Decimalinstead of Double to avoid precision errors.
  3. Memory Optimization:

    • If you don’t need to keep the original array after processing, you can work directly with the same array, reducing memory usage (e.g., use inout for array processing).

Final Notes on Performance:

  • The optimized function already computes the required results in O(n) time complexity with O(1) additional memory usage.
  • These optimizations ensure that the function is fast and uses minimal resources for typical use cases.

Write a program for sorting array. Quick sort, merge sort, Heap Sort

Ans : 

Quick Sorting Integer Array - Explanation


func swap<T: Comparable>(leftValue: inout T, rightValue: inout T) {
    (leftValue, rightValue) = (rightValue, leftValue)
}

func partition<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) -> Int {
    var q = startIndex
    for index in startIndex..<endIndex {
        if array[index] < array[endIndex] {
            swap(leftValue: &array[q], rightValue: &array[index])
            q += 1
        }
    }
    swap(leftValue: &array[q], rightValue: &array[endIndex])
    return q
}
func quickSort<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) {
    // Base case
    if startIndex >= endIndex {
        return
    }
    let placedItemIndex = partition(array: &array, startIndex: startIndex, endIndex: endIndex)
    quickSort(array: &array, startIndex: startIndex, endIndex: placedItemIndex-1)
    quickSort(array: &array, startIndex: placedItemIndex+1, endIndex: endIndex)
}
func quickSort<T: Comparable>(array: inout [T]) {
    quickSort(array: &array, startIndex: 0, endIndex: array.count-1)
}
var numbers = [13, 77, 20, 45, 2, 15, 0, 59, 5, 68, 51, 1, -1, 77]

quickSort(array: &numbers)


Merge Sorting Integer Array - Explanation


func merge<T: Comparable> (array: inout [T], startIndex: Int, middleIndex: Int, endIndex: Int) {
    let leftSubarray = Array(array[startIndex...middleIndex])
    let rightSubarray = Array(array[middleIndex+1...endIndex])
    var index = startIndex
    var leftIndex = 0
    var rightIndex = 0
    while leftIndex < leftSubarray.count && rightIndex < rightSubarray.count {
        if leftSubarray[leftIndex] < rightSubarray[rightIndex] {
            array[index] = leftSubarray[leftIndex]
            leftIndex += 1
        }
        else {
            array[index] = rightSubarray[rightIndex]
            rightIndex += 1
        }
        index += 1
    }
    while leftIndex < leftSubarray.count {
        array[index] = leftSubarray[leftIndex]
        index += 1
        leftIndex += 1
    }
    while rightIndex < rightSubarray.count {
        array[index] = rightSubarray[rightIndex]
        index += 1
        rightIndex += 1
    }
}

func mergeSort<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) {
    // Base case
    if startIndex >= endIndex {
        return
    }
    let middleIndex = (startIndex + endIndex) / 2
    mergeSort(array: &array, startIndex: startIndex, endIndex: middleIndex)
    mergeSort(array: &array, startIndex: middleIndex+1, endIndex: endIndex)
    merge(array: &array, startIndex: startIndex, middleIndex: middleIndex, endIndex: endIndex)
}
func mergeSort<T: Comparable>(array: inout [T]) {
    mergeSort(array: &array, startIndex: 0, endIndex: array.count-1)
}

var numbers = [13, 77, 20, 45, 2, 15, 0, 59, 5, 68, 51, 1, -1, 77]
mergeSort(array: &numbers)





Heap Sorting Integer Array - Explanation

extension Heap {
    public mutating func sort() -> [T] {
        for i in stride(from: (nodes.count - 1), through: 1, by: -1) {
            nodes.swapAt(0, i)
            shiftDown(from: 0, until: i)
        }
        return nodes
    }
}
/*
 Sorts an array using a heap.
 Heapsort can be performed in-place, but it is not a stable sort.
 */
public func heapsort<T>(_ a: [T], _ sort: @escaping (T, T) -> Bool) -> [T] {
    let reverseOrder = { i1, i2 in sort(i2, i1) }
    var h = Heap(array: a, sort: reverseOrder)
    return h.sort()
}

//Testing
func testSort() {
    var h1 = Heap(array: [5, 13, 2, 25, 7, 17, 20, 8, 4], sort: >)
    let a1 = h1.sort()
}

// output : [2, 4, 5, 7, 8, 13, 17, 20, 25]


Write a program for get only numeric from "a,b,1,2,c,4,d,3"

Ans :  

let string = "I have to buy 3 apples, 7 bananas, 10eggs"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let number = Int(item) {
        print("number: \(number)")
    }

}

Output : 

3
7
10


Write a program to swap between two numbers without third variable

Ans : 

For Int : 

var x = 5
var y = 7

x = x + y
y = x - y
x = x - y

print(x)
print(y)


For Other Types :

var a = "a"
var b = "b"
(b, a) = (a, b)



Write program of fast enumeration in swift

Ans : 


  1. enum Beverage: CaseIterable {
  2. case coffee, tea, juice
  3. }
  4. let numberOfChoices = Beverage.allCases.count
  5. print("\(numberOfChoices) beverages available")

  1. for beverage in Beverage.allCases {
  2. print(beverage)
  3. }

Write a program to convert character array to string in Swift

Ans: 

Convert character array to string :

let characterArray: [Character] = ["i", "o", "s", "i", "q", "a", ".", "c", "o", "m"]
let string = String(characterArray)

print(string)

// prints "iosiqa.com"

Convert string array to String : 

let stringArray = ["iosiqa", ".", "com"]
let characterArray = stringArray.flatMap { String.CharacterView($0) }
//let characterArray = stringArray.flatMap { $0.characters } // also works
let string = String(characterArray)

print(string)

// prints "iosiqa.com"

Write a program to remove duplicate elements from array

Ans : 


    Method - 1 : 

    extension Array where Element: Equatable {
        mutating func removeDuplicates() {
            var result = [Element]()
            for value in self {
                if !result.contains(value) {
                    result.append(value)
                }
            }
            self = result
        }
    }


   Use : 


var faa = [3, 0, 1, 0, 3, 1, 2, 0, 1, 2]
faa.removeDuplicates()

output = [3,0,1,2]


Method - 2


 let unique = Array(Set(originals))

Set is collection of unique and unordered elements. So we have converted array to set here to remove duplicate. Output array does not have same order as original.


Write a program to find first 10 prime numbers

Ans : 


     let N = 10
    let maxP = 1000
    var isPrime: [Bool] = []
    var primes: [Int] = []
    
     for i in 0...maxP {
        isPrime.append(true)
    }
    
    isPrime[0] = false
    isPrime[1] = false
    
     for i in 2...maxP {
       if isPrime[i] == true {
          var j = i*i
          while j <= maxP 
               isPrime[j] = false
               j += i
          }
          primes.append(i)
       }
    }
    
    for i in 0..<N {
        print(primes[i])
    }

Write a program to find missing number of array of 1 to n.

Ans : 


      import Foundation
        
        let arr = [1,2,4,5,8,6,9,7]
        let n = arr.count
        let total = ((n + 1)*(n + 2))/2
        var missingNum = total
        for item in arr {
            missingNum = missingNum - item
        }
        print(missingNum)

Write a program to distinguish lowercase and uppercase character from String in swift

Ans : 

Method 1 : 

let string = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
var output = ""

for chr in string {
    var str = String(chr)
    if str.lowercaseString != str {
        output += str
    }
}
print(output)


>>> OSQAVHWPOSI

Method 2 : 

let testString = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
let lowerCase = NSCharacterSet.lowercaseLetterCharacterSet()
let upperCase = NSCharacterSet.uppercaseLetterCharacterSet()

for currentCharacter in testString.utf16 {
  if lowerCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is lowercase.")
  } else if upperCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is UPPERCASE.")
  } else {
    println("Character code \(currentCharacter) is neither upper- nor lowercase.")
  }

}



Method 3 : 

let testString = "Åke röstet un café in Владивосток!"
let lowerCase = CharacterSet.lowercaseLetters
let upperCase = CharacterSet.uppercaseLetters

for currentCharacter in testString.unicodeScalars {
    if lowerCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is lowercase.")
    } else if upperCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is UPPERCASE.")
    } else {
        print("Character code \(currentCharacter) is neither upper- nor lowercase.")
    }
}

Method 4 :   to identify character is uppercase or lowercase

extension Character {

        func isUpperCase() -> Bool {
            return CharacterSet.uppercaseLetters.contains(self.unicodeScalars.first!)
        }

        func isLowerCase() -> Bool {
            return CharacterSet.lowercaseLetters.contains(self.unicodeScalars.first!)
        }


  }

Write a program to reverse string in swift

Ans : 

Using Self made function : 

func reverse(_ s: String) -> String {
       var str = ""
       //.String is just like array of characters

       for character in s.characters {
            str = "\(character)" + str
            print ( str)
       }
   return str
}

print (reverse("!pleH"))


Using Swift Direct method : 

Swift 4.0

let str = "abc"

String(str.reversed())

or 

String(str.characters.reversed())



Write program for ascending sorting Int Array in any language

Ans : 
(Interviewer told syntax doesn't matter, write pseudo-code type program)

1. Not using direct function.

 void main()
    {

        int i, j, a, n, number[30];
        printf("Enter the value of N \n");
        scanf("%d", &n);

        printf("Enter the numbers \n");
        for (i = 0; i < n; ++i)
            scanf("%d", &number[i]);

        for (i = 0; i < n; ++i)
        {

            for (j = i + 1; j < n; ++j)
            {

                if (number[i] > number[j])
                {

                    a =  number[i];
                    number[i] = number[j];
                    number[j] = a;

                }

            }

        }

        printf("The numbers arranged in ascending order are given below \n");
        for (i = 0; i < n; ++i)
            printf("%d\n", number[i]);

    }

2. If we write in swift using higher order function, then

var numbers = [45,6,113,56,8,56,43,78]

print(numbers.sort()) //Sorting in Ascending order

print(numbers.sort(>)) //Sorting in Descending order

Interviewer mostly asked this question to check your programming logic. So he/she don't require syntax.

Q. Sorting strings array
A.
Method 1 : 
var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

Method 2 : 
let sortedNames = names.sort { $0.name < $1.name }
let sortedNames = names.sorted(by: <)


Equilibrium Problem - Left and right side and top and bottom side sum of any point are same in matrix


Problem Description :

#import <Foundation/Foundation.h>


int leftArraySum(NSMutableArray *A,int n)
{
    NSInteger sum  = 0;
    for(int i=0;i<n;i++)
    {
        sum += [[A objectAtIndex:i] integerValue];   
    }
    return sum;
}

int reightArraySum(NSMutableArray *A,int n)
{
     NSInteger sum  = 0;
    for(int i=n+1;i<[A count];i++)
    {
        sum += [[A objectAtIndex:i] integerValue];   
    }
    return sum;
}

int topArraySum(NSMutableArray *A,int n)
{
     NSInteger sum  = 0;
    for(int i=0;i<n;i++)
    {
        sum += [[A objectAtIndex:i] integerValue];   
    }
    return sum;
}

int bottomArraySum(NSMutableArray *A,int n)
{
     NSInteger sum  = 0;
    for(int i=n+1;i<[A count];i++)
    {
        sum += [[A objectAtIndex:i] integerValue];   
    }
    return sum;
}

int solution(NSMutableArray *A) {
    // write your code in Objective-C 2.0
 
    NSMutableArray *rowArr = [A objectAtIndex:0];
    int colCount = [rowArr count];
    int rowCount = [A count];
 
    NSMutableArray *arrRowSum = [[NSMutableArray alloc] initWithCapacity: rowCount];
    NSMutableArray *arrColSum = [[NSMutableArray alloc] initWithCapacity: colCount];
 
    for(int i=0;i<rowCount;i++)
    {
        NSArray *colArr = [A objectAtIndex:i];
        NSNumber * sum = [colArr valueForKeyPath:@"@sum.self"];
        [arrRowSum insertObject:sum atIndex:i];
    }
 
    for(int i=0;i<colCount;i++)
    {
     
        NSInteger sum = 0;
        for(int j=0;j<rowCount;j++)
        {
           sum +=  [[[A objectAtIndex:j] objectAtIndex:i] integerValue];
        }
        NSNumber *sumVal = [NSNumber numberWithInt:sum];
        [arrColSum insertObject:sumVal atIndex:i];
    }
 
    int result = 0;
    for (int i=1;i<rowCount;i++)
    {
        int left = leftArraySum(arrRowSum,i);
        int right = reightArraySum(A,i);
        if(left  == right)
        {
            for(int j=0;j<colCount;j++)
            {
                int top = topArraySum(A,j);
                int bottom = bottomArraySum(A,j);
                   if(top == bottom )
                {
                    result = i+j;
                    break;
                }
            }
        }
    }
 
    return result;
}


Determine index of one integer in another integer - online programming question

Problem Description : Determine index of one integer in another integer

i.e If input A = 23,B = 1472367 then Output : 3 . Because '23' is 3rd index in '1472367'.

Asked in Company : Futurescape Technologies Pvt Ltd  via Codility.com

Ans : 

#import <Foundation/Foundation.h>
// you can also use other imports, for example:
// #import <SomeLibrary/SomeFile.h>

// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");

int solution(int A, int B) {
    // write your code in Objective-C 2.0
    NSString *strA = [NSString stringWithFormat:@"%d",A];
    NSString *strB = [NSString stringWithFormat:@"%d",B];
 
   NSRange range =   [strB rangeOfString:strA];
   if(range.location == NSNotFound)
   return -1;
   else
   return range.location;
}