Group Group Group Group Group Group Group Group Group

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 ?

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"

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,