Start learning free

LESSON 270 OF 674 · TUPLES, SORTING & BUILT-INS

Squares of the Positives in C#: Where, Then Select

Practice Read the full explanation

You get a List of integers, nums.

Return a new List with the square of every number above 0. A number's square is the number times itself.

Keep the squares in the order of their numbers in nums.

Leave out 0 and the negative numbers. If no number is above 0, return an empty List.

 

Example 1:

Input: nums = [3, -1, 0, 4]
Output: [9, 16]
Explanation: Only 3 and 4 are above 0.
3 times 3 is 9, and 4 times 4 is 16.

Example 2:

Input: nums = [-5, -2, 0]
Output: []
Explanation: No number is above 0.

Example 3:

Input: nums = [1, 2, 3]
Output: [1, 4, 9]
Explanation: Every number is above 0, so every number is squared.

 

Constraints:

  • nums may be empty.
  • Every number is between -1000 and 1000.
STEP 1 OF 2
    Ctrl + Enter to check

    C# · TUPLES, SORTING & BUILT-INS

    Positive Squares in C#, explained

    Problem overview

    PositiveSquares gets a List<int> named nums and returns a new List<int> holding the square of every number above 0, in the order of nums. Zero and negative numbers are left out. For [3, -1, 0, 4] the result is [9, 16]. If nothing is above 0, as in [-5, -2, 0], the result is an empty list. The input may itself be empty.

    Approach: filter, then transform

    Two LINQ methods cover the two jobs, and the order matters:

    • Where(num => num > 0) keeps the numbers for which the lambda returns true. Items that fail are dropped.
    • Select(num => num * num) replaces each remaining number with its square.

    The filter must come first. A square is never negative, so squaring first loses the information the filter needs: -3 becomes 9 and then passes > 0. With [3, -1, 0, 4], squaring first and then filtering gives [9, 1, 16], which wrongly includes the square of -1.

    Step by step

    1. Chain the calls on nums: Where to keep the numbers above 0, Select to square them, and ToList() to get a List<int>. Store it in squares.
    2. Return squares. When nothing passes the filter, the list is just empty, which is the right answer.

    The solution in C#

    class Solution {
        public List<int> PositiveSquares(List<int> nums) {
            List<int> squares = nums.Where(num => num > 0).Select(num => num * num).ToList();
            return squares;
        }
    }
    

    Each lambda has its own num. They are separate parameters, so using the same name twice is fine.

    Details that matter

    • Zero is excluded. The test is > 0, not >= 0. Zero is not above 0, and its square would be a stray 0 in the result.
    • Order is kept. Both Where and Select process items in their original order.
    • No overflow here. Numbers are between -1000 and 1000, so a square is at most 1,000,000. An int holds more than two billion. With much larger inputs, num * num would silently wrap around.
    • An empty result is a list, not null. ToList() always gives a list, even with no items.

    The same thing with a loop

    A foreach loop does the filter and the transform in one pass:

    List<int> squares = new List<int>();
    foreach (int num in nums) {
        if (num > 0) {
            squares.Add(num * num);
        }
    }
    return squares;
    

    For [3, -1, 0, 4] it returns [9, 16]. The if is the Where, and the expression inside Add is the Select. In the loop version, the order of the two jobs is built into the code: the test looks at num, and only then is the square computed. The LINQ chain says the same thing in a line, and you read it left to right, as "keep the positives, then square them".

    Pick whichever form you find clearer. The lesson uses the chain because it separates the two ideas, "which numbers" and "what to do with them".

    Testing

    Outputs from running the solution:

    numsResult
    [3, -1, 0, 4][9, 16]
    [-5, -2, 0][]
    [1, 2, 3][1, 4, 9]
    [][]

    Common mistakes

    • Filtering with the wrong test. Writing num != 0 keeps the negative numbers, and num >= 0 keeps zero. The lesson asks for numbers strictly above 0.
    • Select before Where. As shown above, the squares of negative numbers sneak in.
    • Using Math.Pow. It returns a double, so it needs a cast back to int. For a simple square, num * num is shorter and exact.
    • Forgetting ToList(). The method returns a List<int>.
    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free