Review my leetcode solution?

I will grind on leetcode, can anybody review my solution It really help me. I solve this in javascript.
Question Link: https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
Solution:

var kidsWithCandies = function(candies, extraCandies) {
    const maxElement = Math.max(...candies);
    const result = [];
    for (let i = 0; i < candies.length; i++) {
        let candie = candies[i] + extraCandies;
        result.push(candie < maxElement ? false: true)
    }
    return result;
};

And Is wrost time complexity of this code is O(n)?

you don’t need a ternary here, you never need it when you have an expression that evaluates to a boolean

also, yes, it seems time complexity is O(n)

1 Like

The algorithm is sound and optimal, yes this is O(n). The way it is written could be improved slightly:

  1. you do not need to use ternary expressions when the value you are assigning as a result are boolean.
const c=a<=b; //c is true when a <= b, false when a > b
const c=a>b?false:true // same as above
  1. Since you are going over the totality of an array to form an entirely new array, this is the perfect opportunity to use Array.prototype.map()
1 Like