Day 7: HackerRank 30 Days Of Code Solution | Arrays

Day 7: HackerRank 30 Days Of Code Solution | Arrays

Day 7 of HackerRank's 30 Days of Code introduces arrays. The task is to read some numbers and print them backwards. That is about as simple as array problems get, but it covers the basics you will use every day: creating an array of the right size, filling it from input, and walking it with an index in either direction.

It is also a good place to pick up two habits early. Use one Scanner for input, and build output with a StringBuilder instead of joining strings in a loop. Both matter once inputs get large.

Problem

An array holds values of one type in a row, and you reach each one by its index. You are given N integers. Print them in reverse order on one line, with a single space between neighbouring numbers.

Input: the first line has N, how many numbers there are. The second line has the N numbers separated by spaces.

Output: the same N numbers in reverse order on one line, separated by spaces.

Constraints: 1 ≤ N ≤ 1000, and each number Ai is between 1 and 10000.

Input:
4
1 4 3 2

Output:
2 3 4 1

Approach

  1. Read N and create int[] arr = new int[n]. Arrays in Java have a fixed size, so you need N before creating it.
  2. Fill it with a loop from index 0 to n - 1, reading one number each time.
  3. Walk backwards from index n - 1 down to 0 and add each number to the output.
  4. Put a space after every number except the last one printed (the one at index 0).

Why not just print in the loop with System.out.print(arr[i] + " ")? It works, and HackerRank usually ignores a trailing space. But many judges do not, so it is better to control the separator yourself. The if (i > 0) check adds a space only between numbers.

You might wonder if you need the array at all. Since you have to print the last number first, and you only see it after reading everything, yes, you must store the values somewhere before printing.

Dry run with 1 4 3 2: after reading, arr = [1, 4, 3, 2]. Start at i = 3: append 2 and a space. i = 2: append 3 and a space. i = 1: append 4 and a space. i = 0: append 1, no space. The result is "2 3 4 1".

Solution in Java

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);   // one Scanner for System.in, not two
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        sc.close();

        // Build the output once instead of joining Strings in a loop
        StringBuilder sb = new StringBuilder();
        for (int i = n - 1; i >= 0; i--) {
            sb.append(arr[i]);
            if (i > 0) {
                sb.append(' ');   // space between numbers, none at the end
            }
        }
        System.out.println(sb);
    }
}

What I changed from the old code. The previous version on this page had its Java code split into two broken pieces with a stray comment between them. It also created two Scanner objects on System.in (one unused), and joined the output with result = result + array[i] + " ". Two scanners on the same stream is a real bug waiting to happen, because the first one can buffer input that the second never sees. And since Strings are immutable, each + in a loop copies the whole string again, which is O(n2) work in total. A single scanner and a StringBuilder fix both. The old version also printed a trailing space, which the code above avoids.

Tests I ran:

  • The sample prints 2 3 4 1 with no trailing space (I checked the raw output).
  • N = 1 with the number 7 prints 7. The loop runs once and no space is added.

Output

2 3 4 1

Complexity

Time: O(N). One pass to read and one pass to build the output.

Space: O(N) for the array and the output buffer.

Variations

  • Reverse in place. Swap arr[i] with arr[n - 1 - i] for i from 0 to n/2 - 1, then print normally. This is the version interviewers ask for, because it uses O(1) extra space for the reversal.
  • Using collections. Read into an ArrayList<Integer> and call Collections.reverse(list). Handy in real code, but know the manual loop first.
  • Using a stack. Push every number, then pop them all. The last in comes out first, which naturally reverses the order. This is a good warm-up for Day 18: Queues and Stacks.
  • Faster input. For very large N, BufferedReader with a StringTokenizer is much faster than Scanner.

Next in the series: Day 8: Dictionaries and Maps. For more array practice in Java, see Java 1D Array.

Tip: try to solve the problem yourself before reading the solution. Use the code as a reference to check your approach, and make sure you understand why it works.

More HackerRank solutions All coding problems MCQ practice

Comments

Answered 0/0Correct 0