Day 6: HackerRank 30 Days Of Code Solution | Let's Review

Day 6: HackerRank 30 Days Of Code Solution | Let's Review

Day 6 of 30 Days of Code is called "Let's Review" because it pulls together what the first five days covered: reading input, loops, conditions and output. You get a few words, and for each word you print the characters at even positions, a space, then the characters at odd positions. "Hacker" becomes Hce akr.

Under the surface this problem is about two things beginners often find confusing: strings are indexed from 0, and mixing nextInt() with nextLine() in Java can quietly eat a line of your input. Once you understand both, a whole class of "my output is shifted by one" and "my program skipped a line" bugs disappears.

Problem

You get T strings. For each string S, split its characters into two groups by position: positions 0, 2, 4, ... (even) and positions 1, 3, 5, ... (odd). Print the even group, then a single space, then the odd group, all on one line. Position 0 counts as even.

Input format: the first line contains T. Each of the next T lines contains one string S.

Output format: T lines, each with two space-separated strings as described.

Constraints: 1 ≤ T ≤ 10, 2 ≤ length of S ≤ 10000.

Input:
2
Hacker
Rank

Output:
Hce akr
Rn ak

Approach

Think of a string as a row of numbered boxes, starting at box 0. "Hacker" is H(0) a(1) c(2) k(3) e(4) r(5). You need to walk through the boxes once and drop each character into one of two bags: the even bag or the odd bag. The test for which bag is i % 2 == 0, the same remainder trick used for odd and even numbers.

  1. Read T.
  2. Repeat T times: read the next full line as S.
  3. Create two empty builders, even and odd.
  4. Loop i from 0 to S.length() - 1. Append S.charAt(i) to even if i is even, otherwise to odd.
  5. Print even + " " + odd.

Dry run on "Rank": i = 0 puts R in even, i = 1 puts a in odd, i = 2 puts n in even, i = 3 puts k in odd. The bags are "Rn" and "ak", so we print Rn ak.

A one-pass loop is enough. You do not need to loop twice (once for even, once for odd), though that also works.

Solution in Java

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = Integer.parseInt(in.nextLine().trim()); // read the count as a full line

        for (int k = 0; k < t; k++) {
            String s = in.nextLine();
            StringBuilder even = new StringBuilder();
            StringBuilder odd = new StringBuilder();

            for (int i = 0; i < s.length(); i++) {
                if (i % 2 == 0) {
                    even.append(s.charAt(i));
                } else {
                    odd.append(s.charAt(i));
                }
            }
            System.out.println(even + " " + odd);
        }
        in.close();
    }
}

The Java parts explained:

  • in.nextLine() for the count: this is the key choice. If you read T with nextInt(), Scanner reads the digits but leaves the newline at the end of that line. Your first nextLine() then returns an empty string, and every word after that is off by one. Reading the whole first line and converting it with Integer.parseInt() avoids the problem completely. (Calling an extra nextLine() after nextInt() also works; the old solution here did that.)
  • trim() removes stray spaces around the number so parseInt does not fail on input like "2 ".
  • s.charAt(i) returns the character at position i. Positions start at 0 and end at s.length() - 1.
  • StringBuilder is a string you can grow cheaply. With strings up to 10,000 characters, building the result with += on a normal String would create a new copy every time, which is slow. append() just adds to the end.

The previous solution printed characters one at a time and looped over the string twice. It was correct. This version does one pass and prints each line once, which is cleaner and faster for long strings.

Besides the sample, I tested "ab" (prints a b, the smallest allowed length) and "abc" (prints ac b, where the odd-length string gives the even half one extra character).

Output

Hce akr
Rn ak

Complexity

Each character is visited once, so time is O(total length of all strings). Extra space is O(length of S) for the two builders.

Common mistakes

  • The nextInt() then nextLine() trap: the first string read comes back empty and the output has one wrong line. Read the whole line or consume the leftover newline.
  • Treating position 1 as the first even position. Java indexes from 0, and 0 is even.
  • Printing a newline between the two halves, or forgetting the space.
  • Using in.next() for the strings. That works for this input because there are no spaces, but it is a fragile habit if a later problem includes spaces.

Previous: Day 5: Loops. Next: Day 7: Arrays.

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

HackerRank 30 Days of Code: ← Previous: Day 5: Loops |  |  Next: Day 7: Arrays | →
See everything in one place: Coding Problems and Solutions

Comments

Answered 0/0Correct 0