Heap Challenge 1 - Chapter 23

Cha

Heap Data Structure Challenges

Challenge 1:

Write a function to find the nth smallest integer in an unsorted array. For example:


let integers = [3, 10, 18, 5, 21, 100]

n = 3

If n = 3, the result should be 10.

*/

func getNthSmallestElement(n: Int, elements: [Int]) β†’ Int? {

// Your code here

return nil

}

let elements = [3, 10, 18, 5, 21, 100]

let nthElement = getNthSmallestElement(n: 3, elements: elements)

why if n = 3 the result should be 10?
what i am missing what i understand
Write a function to find the nth smallest integer in an unsorted array.
then it will be 3 from our this array > [3, 10, 18, 5, 21, 100] becz 3 is most smallest yes?
we dont search by index here we are searching smallest integer if yes it should be 3 ?

1 Like

I feel that the expected output for this challenge is unclear, too. Does this mean that depending upon the input value of n, then the output result should be the next element in the given array?

For instance:

if n = 10, the result should be 18
if n = 100, the result should be nil
if n = 21, the result should be 100

If that is the case, here’s my solution that you can copy and paste into a Playground:

func getNthSmallestElement(n: Int, elements: [Int]) -> Int? {
    if n != elements.last {
        for elementIndex in 0..<elements.count {
            if elements[elementIndex] == n {
                return elements[elementIndex + 1]
            }
        }
    }
return nil
}

let elements = [3, 10, 18, 5, 21, 100]

let nthElement = getNthSmallestElement(n: 3, elements: elements)

print("nthElement: \(nthElement ?? 0)") // <- Result is "nthElement: 10"
1 Like

Hi @alif,
Your question is quite valid and I would also understand the question the same way.

@oogafish, your interpretation is not bad and your code works based on those assumptions.

thanks,

Hi :relaxed:
The goal of the challenge is not to find the absolute smallest value contained in the collection, but to find the nth element with the smallest value.
The proposed collection contains the values 3, 10, 18, 5, 21, 100.
The smallest value contained in the collection is 3, so looking for the second smallest value we will get 5, looking for the third (as in the example) we will get 10, looking for the fourth we will get 18, etc.