LeetCode 500: Keyboard Row Solution

Master LeetCode problem 500 (Keyboard Row), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

500. Keyboard Row

Problem Explanation

Explanation:

  • Create a set for each row of the keyboard with the characters in that row.
  • Iterate over each word in the input array and check if all characters in the word belong to the same row of the keyboard.
  • If a word meets the criteria, add it to the result list.

Time Complexity: O(n * m) where n is the number of words and m is the average length of a word. Space Complexity: O(1) since the size of the keyboard rows is fixed.

:

Solution Code

class Solution {
    public String[] findWords(String[] words) {
        String[] rows = new String[]{"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        List<String> result = new ArrayList<>();
        
        for (String word : words) {
            if (checkWordInRow(word.toLowerCase(), rows)) {
                result.add(word);
            }
        }
        
        return result.toArray(new String[result.size()]);
    }
    
    private boolean checkWordInRow(String word, String[] rows) {
        for (String row : rows) {
            boolean inSameRow = true;
            for (char c : word.toCharArray()) {
                if (row.indexOf(c) == -1) {
                    inSameRow = false;
                    break;
                }
            }
            if (inSameRow) {
                return true;
            }
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 500 (Keyboard Row)?

This page provides optimized solutions for LeetCode problem 500 (Keyboard Row) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 500 (Keyboard Row)?

The time complexity for LeetCode 500 (Keyboard Row) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 500 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 500 in Java, C++, or Python.

Back to LeetCode Solutions