• + 16 comments

    Efficient JavaScript solution

    The algorithm doesn't count the string a second time, both best and worst case is O(n) where n = length of the string

    From my repo https://github.com/gabrielgiordan/HackerRank

    function repeatedString(s, n) {
      let c = 0,
          ca = 0,
          r = n % s.length
    
      for (let i = s.length; i-- > 0;) {
        if (s.charAt(i) == 'a') {
          ++c
    
          if (i < r)
            ++ca
        }
      }
    
      return ((n - r) / s.length * c) + ca
    }