Keyboard Row Solution in Java

Problem Description

So, you think typing is easy? Well, let’s throw a curveball at you! The problem is called “Keyboard Row,” and it’s not just about typing; it’s about figuring out which words can be typed using letters from the same row of a QWERTY keyboard. Yes, that’s right! You can’t just type any word; it has to be a word that fits snugly in one row.

Imagine you’re at a party, and you can only talk to people who are standing in the same row as you. If someone from another row tries to join the conversation, you just can’t handle it! That’s the essence of this problem.

The Keyboard Layout

Row 1: Q W E R T Y U I O P
Row 2: A S D F G H J K L
Row 3: Z X C V B N M

Code Solution

class Solution {
  public String[] findWords(String[] words) {
    List ans = new ArrayList<>();
    final int[] rows = {2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3,
                        3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3};

    for (final String word : words) {
      final String lowerWord = word.toLowerCase();
      final int row = rows[lowerWord.charAt(0) - 'a'];
      final boolean isValid = lowerWord.chars().allMatch(c -> rows[c - 'a'] == row);
      if (isValid)
        ans.add(word);
    }

    return ans.toArray(new String[0]);
  }
}

Approach

The approach taken in this solution is straightforward yet effective. It uses an integer array to represent which row each letter belongs to. For each word, it checks if all characters belong to the same row by comparing their corresponding values in the rows array. If they do, the word is added to the result list.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(N * M), where N is the number of words and M is the average length of the words.
Space Complexity O(K), where K is the number of valid words that can be formed.

Real-World Example

Think of it this way: you’re at a concert, and you can only dance with people in your row. If someone from the back row tries to join you, it’s just not going to work out. Similarly, the “Keyboard Row” problem restricts words to those that can be typed using letters from the same row of the keyboard.

Similar Problems

If you enjoyed this problem, you might also like these:

  • Two Sum Solution in Java
  • Three Sum Solution in Java
  • Four Sum Solution in Java