Create and Fill an Array of Squares

Solve this Problem
Easy5 min
Topics
Companies
Given n, create and return an array of length n whose element at index i is (i + 1)² — the squares 1, 4, 9, …, n². An arrayArrayA fixed-length sequence of values of the same type, stored side by side and accessed by index starting at 0. holds a sequence of values that you reach by position, starting from index 0Zero-Based IndexingCounting positions from 0, so the first element is at index 0 and the last at index length − 1.. There are two everyday ways to build one: create it at its final size and fill each slot, or start empty and append values one at a time. Printing the result (as you would in a real program) is just a loop over the finished array.

Test Case 1:

Input:n = 5
Output:[1, 4, 9, 16, 25]
Explanation:Position i holds (i + 1)², so the array starts at 1 and ends at n².

Test Case 2:

Input:n = 1
Output:[1]
Explanation:An array of size one.

Constraints

  • ◆1 ≤ n ≤ 1000

Try the Dry Run

Approach & Solutions

Fill a Fixed-Size Array by IndexOptimal

The size is known in advance — exactly n values — so create an array of length n first and then fill each position i with (i + 1)². Creating it once with the right size is the most direct way to build an array.

TimeO(n)
SpaceO(n)
class Solution { public int[] squaresUpTo(int n) { int[] squares = new int[n]; for (int i = 0; i < n; i++) { squares[i] = (i + 1) * (i + 1); } return squares; } }
Grow a List by AppendingGood

Start with an empty, growable list and append each square in turn. This is the natural choice when the final size is not known in advance. C has no growable array, so it enlarges its block with realloc on every append — which shows the hidden cost of growing.

TimeO(n)
SpaceO(n)
class Solution { public int[] squaresUpTo(int n) { List<Integer> squares = new ArrayList<>(); for (int i = 1; i <= n; i++) { squares.add(i * i); } return squares.stream().mapToInt(Integer::intValue).toArray(); } }

Related Problems