1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【備忘録】Codewar(JavaScript)勉強記録

Posted at

Codewar を使い始めたので自分用アウトプット記録。

JavaScript をもっと使えるようになりたいのと、就活中なので始めてみた。
Time Complexity とかも考えて効率的で良いコードが書けるようになりたい。

1. Even or Odd

パラメータの数字から偶数であれば、true。奇数であれば false を返す関数を作る。

Time Complexity: O(1)

処理自体は一回

Space Complexity: O(1)

function even_or_odd(number) {
  // check parameter
  if (typeof number !== 'number') return;
  // if it can be devided by 2, return even
  if (number % 2 === 0) return 'Even';
  else return 'Odd';
}

ベストプラクティス参考

Ternary Operator できれい。

function even_or_odd(number) {
  return number % 2 ? 'Odd' : 'Even';
}

2. Isograms

パラメータに重複する文字があれば、false、全部ユニークであれば true を返す。

// '' -> true
// 'dermatoglyphics' -> true
// 'aba' -> false
// 'moOse' -> false (ignore letter case)

2 - 1. Brute Force

Time Complexity: O(N^2);

nested loop

Space Complexity: O(1);

Check through each parameters and compare each letter with other letters using nested loop to check if the letter is the same

// aba   : length 3
function isIsogram(str) {
  //check parameter
  if (str.length <= 1) return true;
  for (let i = 0; i < str.length; i++) {
    if (i === str.length - 1) {
      return true;
    } else {
      for (let j = i + 1; j < str.length; j++) {
        if (str[i].toLowerCase() === str[j].toLowerCase()) return false;
      }
    }
  }
  return true;
}

2 - 2. Hashmap

Time Complexity: O(N)

1 loop

Space Complexity: O(1)

Check through each parameters, and store it as key, if there is already value, return

function isIsogram(str) {
  //create Hashmap
  let map = new Map();
  for (let i = 0; i < str.length; i++) {
    let s = str[i].toLowerCase();
    if (map.get(s) !== undefined) {
      return false;
    }
    map.set(s, s);
  }
  return true;
}

ベストプラクティス参考

Set(キーなしの値の集合)
それぞれの値を Set に入れて、そのサイズがパラメータの数と同じであれば、重複がない!

function isIsogram(str) {
  return new Set(str.toUpperCase()).size == str.length;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?