500. Keyboard Row

2026-03-25
리트코드 500번 풀이

문제

Keyboard Row

풀이

아이디어

키보드의 각 행을 Set으로 만들어두고, 각 단어의 첫 글자가 속한 행을 찾은 뒤 나머지 글자들이 모두 같은 행에 있는지 확인한다.

풀고 나서 알았지만, 동일한 로직을 map, some, every를 이용해서 간결하게 코드를 작성할수도 있다.

코드

function findWords(words: string[]): string[] {
  const rows: Set<string>[] = [new Set('qwertyuiop'), new Set('asdfghjkl'), new Set('zxcvbnm')];
  const ans: string[] = [];

  for (const word of words) {
    const lowerWord = word.toLowerCase();
    let rowIdx = 0;
    while (!rows[rowIdx].has(lowerWord[0])) rowIdx++;

    let isPossible = true;
    for (let idx = 1; idx < lowerWord.length; idx++) {
      if (!rows[rowIdx].has(lowerWord[idx])) {
        isPossible = false;
        break;
      }
    }

    if (isPossible) ans.push(word);
  }

  return ans;
}

고차함수를 이용한 더 간결한 풀이

function findWords(words: string[]): string[] {
  const rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'].map(r => new Set(r));

  return words.filter(word => {
    const lower = word.toLowerCase();
    return rows.some(row => lower.split('').every(c => row.has(c)));
  });
}

시간 / 공간 복잡도

  • 시간 복잡도: O(n * m) — n: 단어 수, m: 단어 평균 길이
  • 공간 복잡도: O(1) — 키보드 행 Set 크기는 고정 (26자)