We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Implementation
  4. Repeated String
  5. Discussions

Repeated String

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • gabrielgiordano
    4 years ago+ 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
    }
    
    44|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature