Print Odd Numbers from 1 to N
Solve this ProblemEasy5–10 min
Topics
BasicsLoops
Companies
TCSInfosysWipro
Given a non-negative integer
n, return every odd number from 1 up to and including n, in increasing order.
The check-every-numberCheck Every NumberWalking through every integer from 1 to n and testing i % 2 != 0 before deciding whether to keep it. version mirrors the even-number check exactly, just flipping the condition. The step-by-2Step by 2Starting at 1 and incrementing by 2 each time, so every value visited is already odd. version again skips the wasted half of the work by construction, starting at 1 instead of 2.
Test Case 1:
Input:n = 10
Output:[1, 3, 5, 7, 9]
Explanation:Every odd number from 1 up to 10.
Test Case 2:
Input:n = 1
Output:[1]
Explanation:The only odd number up to 1.
Test Case 3:
Input:n = 2
Output:[1]
Explanation:2 itself is even, so only 1 qualifies.
Constraints
- ◆
0 ≤ n ≤ 1000
Try the Dry Run
Approach & Solutions
Check Every Number with % 2Good
Walk i through every number from 1 to n, testing each one with i % 2 != 0 before deciding whether to keep it — the mirror image of checking for evens.
Time
O(n)Space
O(n/2) for the outputJava
1class Solution {
2 public int[] printOddNumbers(int n) {
3 List<Integer> odds = new ArrayList<>();
4 for (int i = 1; i <= n; i++) {
5 if (i % 2 != 0) {
6 odds.add(i);
7 }
8 }
9 int[] result = new int[odds.size()];
10 for (int k = 0; k < odds.size(); k++) {
11 result[k] = odds.get(k);
12 }
13 return result;
14 }
15}Step by 2 from the StartOptimal
Start i at 1 (the first odd number) and jump by 2 every time, so every value visited is already odd — no modulo check needed, and about half as many iterations as checking every number.
Time
O(n/2)Space
O(n/2)Java
1class Solution {
2 public int[] printOddNumbers(int n) {
3 List<Integer> odds = new ArrayList<>();
4 for (int i = 1; i <= n; i += 2) {
5 odds.add(i);
6 }
7 int[] result = new int[odds.size()];
8 for (int k = 0; k < odds.size(); k++) {
9 result[k] = odds.get(k);
10 }
11 return result;
12 }
13}