How to group elements of an array based on their first occurrence in Swift

1 Answer

0 votes
import Foundation

let MAX_VALUE = 100 // Assumes values are between 0 and 99

func groupElements(_ arr: [Int]) -> [Int] {
    var frequency = Array(repeating: 0, count: MAX_VALUE)
    var order: [Int] = []
    var result: [Int] = []

    // Count frequencies and track order of first occurrences
    for num in arr {
        if frequency[num] == 0 {
            order.append(num)
        }
        frequency[num] += 1
    }

    // Group elements based on their first occurrence
    for num in order {
        result += Array(repeating: num, count: frequency[num])
    }

    return result
}

let arr = [88, 33, 77, 88, 22, 55, 88, 55, 11, 99, 88, 11, 77]
let grouped = groupElements(arr)

print("Grouped vector:", grouped.map { String($0) }.joined(separator: " "))



/*
run:

Grouped vector: 88 88 88 88 33 77 77 22 55 55 11 11 99

*/

 



answered Oct 11, 2025 by avibootz
...