Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

  • the first row consists of the characters "qwertyuiop ",
  • the second row consists of the characters "asdfghjkl ", and
  • the third row consists of the characters "zxcvbnm ".

Example 1:

Input: words = [ "Hello ", "Alaska ", "Dad ", "Peace "] Output: [ "Alaska ", "Dad "]

Example 2:

Input: words = [ "omk "] Output: []

Example 3:

Input: words = [ "adsdf ", "sfd "] Output: [ "adsdf ", "sfd "]

Constraints:

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] consists of English letters (both lowercase and uppercase).

Note: This problem is from LeetCode.
❌ Compiled
❌ Executed
❌ Correct
program main
    implicit none

    integer, parameter :: n_examples = 3
    character(len=50), dimension(n_examples) :: examples
    character(len=50), allocatable :: words(:)
    integer :: i, j, k

    examples(1) = "Hello "
    examples(2) = "Alaska "
    examples(3) = "Dad "
    examples(4) = "Peace "
    examples(5) = "omk "
    examples(6) = "adsdf "
    examples(7) = "sfd "

    do i = 1, n_examples
        call get_words(examples(i), words)
        write (*, '(A)') trim(examples(i)) // ': '
        do j = 1, size(words)
            write (*, '(A)', advance='no') trim(words(j)) // ', '
        end do
        write (*, *) ''
    end do

contains

    subroutine get_words(word, words)
        implicit none
        character(*), intent(in) :: word
        character(len=*), allocatable, intent(out) :: words(:)
        integer :: i, j, k, l, m, n
        character(len=1) :: c
        logical :: found

        allocate(words(size(word)))

        ! Initialize the list of words
        words = ''

        ! Loop over each letter in the word
        do i = 1, len(word)
            c = word(i:i)

            ! Check if the letter is already in the list of words
            found = .false.
            do j = 1, size(words)
                if (c == words(j)(1:1)) then
                    found = .true.
                    exit
                end if
            end do

            ! If the letter is not already in the list of words, add it
            if (.not. found) then
                allocate(character(len=1) :: words(size(words)+1))
                words(size(words)) = c
            end if
        end do

        ! Remove duplicates from the list of words
        do i = 1, size(words)-1
            do j = i+1, size(words)
                if (words(i) == words(j)) then
                    words(j) = words(size(words))
                    deallocate(words(size(words)))
                    exit
                end if
            end do
        end do

    end subroutine get_words

end program main
❌ Compiled
❌ Executed
❌ Correct
! Declare variables
integer :: i, j, k, n, m
character(len=100) :: words(20)
character(len=100) :: alphabet(3, 10)
character(len=100) :: result(20)
integer :: result_index

! Initialize variables
n = size(words)
m = 0
result_index = 0

! Initialize alphabet
alphabet(1, :) = "qwertyuiop "
alphabet(2, :) = "asdfghjkl "
alphabet(3, :) = "zxcvbnm "

! Loop through each word
do i = 1, n
    ! Loop through each character in the word
    do j = 1, len_trim(words(i))
        ! Check if the character is in the alphabet
        do k = 1, 3
            if (index(alphabet(k, :), words(i)(j:j)) /= 0) then
                ! If the character is in the alphabet, add it to the result
                result(result_index) = words(i)(j:j)
                result_index = result_index + 1
                exit
            end if
        end do
    end do
end do

! Print the result
do i = 1, result_index - 1
    write (*, *) result(i)
end do

end
🌐 Data from online sources
def find_words(words):
    rows = [
        set("qwertyuiopQWERTYUIOP"),
        set("asdfghjklASDFGHJKL"),
        set("zxcvbnmZXCVBNM")
    ]
    res = []

    for word in words:
        row = -1
        for i in range(3):
            if word[0] in rows[i]:
                row = i
                break

        if all(c in rows[row] for c in word):
            res.append(word)

    return res
1. Create an array of sets representing each row of the American keyboard. Include both uppercase and lowercase letters in the set.
  1. Initialize an empty result list.
  2. Loop through the input words array.
  3. Determine the row of the first character of the current word by checking which of the 3 rows contains it.
  4. Check if all the characters in the current word belong to the same row found in step 4. If yes, append the word to the result list.
  5. Once the loop is done, return the result list.
🌐 Data from online sources
#include <vector>
#include <string>
#include <unordered_set>
using namespace std;

vector<string> findWords(vector<string>& words) {
    vector<unordered_set<char>> rows = {
        {'q','w','e','r','t','y','u','i','o','p'},
        {'a','s','d','f','g','h','j','k','l'},
        {'z','x','c','v','b','n','m'}
    };
    vector<string> result;

    for (const auto& word : words) {
        int row = -1;
        for (int i = 0; i < 3; ++i) {
            if (rows[i].count(tolower(word[0])) > 0) {
                row = i;
                break;
            }
        }

        bool isOneRow = true;
        for (const auto& letter : word) {
            if (rows[row].count(tolower(letter)) == 0) {
                isOneRow = false;
                break;
            }
        }

        if (isOneRow) {
            result.push_back(word);
        }
    }

    return result;
}
1. Create an array of sets representing each row of the American keyboard. Include both uppercase and lowercase letters in the set.
  1. Initialize an empty result list.
  2. Loop through the input words array.
  3. Determine the row of the first character of the current word by checking which of the 3 rows contains it.
  4. Check if all the characters in the current word belong to the same row found in step 4. If yes, append the word to the result list.
  5. Once the loop is done, return the result list.