DEV Community

Cover image for Special Array With X Elements Greater Than or Equal X (Go)
Muhamad Taufik Satya
Muhamad Taufik Satya

Posted on

Special Array With X Elements Greater Than or Equal X (Go)

On May 27 2024, I encountered a daily Leetcode challenge entitled

Special Array With X Elements Greater Than or Equal X

This challenge is relatively easy and quite friendly for beginners to practice. Because I'm learning Golang, I implemented it using that language.

For the question link, you can go to the following page.

Question description

Example questions

Solution

First of all, let's define the function.

func specialArray(nums []int) int {

}
Enter fullscreen mode Exit fullscreen mode

Then, initiate the loop and associated dependent variables such as x and count into the function.

func specialArray(nums []int) int {
    for i := 1; i <= len(nums); i++ {
        x := i
        count := 0
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, loop back over the nums array to compare whether each element is greater than x, if yes, add it to the count variable.

for _, v := range nums {
    if v >= x {
        count++
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, check whether count is the same as x, if it is, immediately return x. However, if not, at the end of the function add return -1.

if count == x {
    return x
}
Enter fullscreen mode Exit fullscreen mode

Complete code:

func specialArray(nums []int) int {
    for i := 1; i <= len(nums); i++ {
        x := i
        count := 0

        for _, v := range nums {
            if v >= x {
                count++
            }
        }

        if count == x {
            return x
        }
    }

    return -1
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)