
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.
- Read
T. - Repeat
Ttimes: read the next full line asS. - Create two empty builders,
evenandodd. - Loop
ifrom 0 toS.length() - 1. AppendS.charAt(i)toevenifiis even, otherwise toodd. - 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 readTwithnextInt(), Scanner reads the digits but leaves the newline at the end of that line. Your firstnextLine()then returns an empty string, and every word after that is off by one. Reading the whole first line and converting it withInteger.parseInt()avoids the problem completely. (Calling an extranextLine()afternextInt()also works; the old solution here did that.)trim()removes stray spaces around the number soparseIntdoes not fail on input like"2 ".s.charAt(i)returns the character at positioni. Positions start at 0 and end ats.length() - 1.StringBuilderis a string you can grow cheaply. With strings up to 10,000 characters, building the result with+=on a normalStringwould 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()thennextLine()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
See everything in one place: Coding Problems and Solutions
Comments
Post a Comment