Grokking Oracle Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
Nomad Phantom
Is this O(n^2)??

Nomad Phantom

Oct 11, 2024

func findTripletSumToZero(arr: [Int]) -> [[Int]] {

    let set = Set(arr)

    var triplets = Set<Set<Int>>()

    var i = 0

    var j = 1

    while (i < arr.count && j < arr.count) {

        if (!set.contains(-1 * (arr[i] + arr[j]))) {

            if (i == j) {

                j += 2

            } else {

                j += 1

            }

        } else {

            let triplet = Set([arr[i], arr[j], -1 * (arr[i] + arr[j])])

            if (!triplets.contains(triplet)) {

                triplets.insert(triplet)

            }

            if (i == j) {

                i += 2

            } else {

                i += 1

            }

        }

    }

    return triplets.map { set in

        set.map { elem in

            elem

        }

    }

}

0

0

Comments
Comments
Hack Point
Hack Point2 months ago
I think this question is always O(n^3), the space should be O(1) Your solution doesn't answer these requirements, public List<List<int>> SearchTriplets(int[] arr) { Array.Sort(arr); List<List<int>> triplets = new List<List<int>>(); int n = arr...

On this page