DEV Community

Cover image for Coding interviews asked programs
Harsh Prajapat
Harsh Prajapat

Posted on

Coding interviews asked programs

Program to demonstrate max & min

var arr = [2, 8, 4, 9, 3]
var max = arr[0]
var min = arr[0]

for i in 0..<arr.count {
    if arr[i] > max {
        max = arr[i]
    }

    if arr[i] < min {
        min = arr[i]
    }
}

print(max) // 9
print(min) // 2

Enter fullscreen mode Exit fullscreen mode

Program to demonstrate Second Largest

var arr = [2, 8, 4, 9, 3]
var max = arr[0]
var secondLarget = arr[0]

for i in 0..<arr.count {
    if arr[i] > max {
        secondLarget = max
        max = arr[i]
    } else if arr[i] > secondLarget && arr[i] != max {
        secondLarget =  arr[i]
    }
}

print(max) // 9
print(secondLarget) // 8
Enter fullscreen mode Exit fullscreen mode

✅ Swift: Find Two Numbers That Sum to a Target

- Using loop

let arr = [2, 7, 11, 15]
let target = 9

for i in 0..<arr.count {
    for j in i+1..<arr.count {
        if arr[i] + arr[j] == target {
            print("Pair: (\(arr[i]), \(arr[j]))")
        }
    }
}

Output: Pair: (2, 7)
Enter fullscreen mode Exit fullscreen mode

Program to demonstrate duplicates values program

let arr = [2, 7, 3, 8, 2, 9, 8, 3]
var duplicates = Set<Int>()

for i in 0..<arr.count {
    for j in i+1..<arr.count {
        if arr[i] == arr[j] {
            duplicates.insert(arr[i])
        }
    }
}
print("duplicates: \(duplicates) & count: \(duplicates.count)")
// duplicates: [2, 3, 8] & count: 3
Enter fullscreen mode Exit fullscreen mode

Program to demonstrate PrintNumberTriangle

func printNumberTriangle(rows: Int) {
    for i in 1...rows {
        var line = ""
        for j in 1...i {
            line += "\(j) "
        }
        print(line.trimmingCharacters(in: .whitespaces))
    }
}
printNumberTriangle(rows: 5)

**Output:**
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)