Print Numbers from 1 to N
Solve this ProblemEasy5 min
Topics
BasicsLoops
Companies
TCSInfosysWipro
Given a non-negative integer
n, return the numbers from 1 to n, in increasing order.
The for loopFor LoopWalking an index from 1 to n, appending each value as it goes. version is the most literal reading of the problem. The built-in rangeBuilt-in Range GenerationA language feature that produces a contiguous sequence of numbers directly, without the programmer tracking an index. version reaches for whatever range-generation tool a language already provides — still the same O(n) amount of work, just expressed without writing the loop by hand.
Test Case 1:
Input:n = 5
Output:[1, 2, 3, 4, 5]
Explanation:Every integer from 1 up to 5, in order.
Test Case 2:
Input:n = 1
Output:[1]
Explanation:Just the one number.
Test Case 3:
Input:n = 0
Output:[]
Explanation:No numbers to print.
Constraints
- ◆
0 ≤ n ≤ 1000
Try the Dry Run
Approach & Solutions
For LoopGood
Walk i from 1 up to n, appending each value as the loop goes. The most direct reading of "every number from 1 to n."
Time
O(n)Space
O(n) for the outputJava
1class Solution {
2 public int[] printOneToN(int n) {
3 int[] result = new int[n];
4 for (int i = 1; i <= n; i++) {
5 result[i - 1] = i;
6 }
7 return result;
8 }
9}Built-in Range GenerationOptimal
Many languages can generate a contiguous range directly, without the programmer tracking an index or calling append one value at a time. C has no such built-in, so it still reaches for the explicit loop — but Java, Python, C++, and JavaScript can each produce [1, 2, ..., n] in a single expression.
Time
O(n)Space
O(n)Java
1class Solution {
2 public int[] printOneToN(int n) {
3 return java.util.stream.IntStream.rangeClosed(1, n).toArray();
4 }
5}