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.
Repeated String
Repeated String
+ 78 comments Use Python 3:
s, n = input().strip(), int(input().strip()) print(s.count("a") * (n // len(s)) + s[:n % len(s)].count("a"))
+ 30 comments public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); long n = in.nextLong(); long count =0; for(char c : s.toCharArray()) if(c == 'a') count++; long factor = (n/s.length()); long rem = (n%s.length()); count = factor*count ; for(int i=0;i<rem;i++) if(s.charAt(i)=='a') count++; System.out.println(count); }
+ 3 comments When you get time-outs, you are probably trying to construct the 'infinite' string based on the amount of chars you need. Don't do this, but instead count the number of 'a's in the original string and then multiply this till you get to the target. The remaining part of a string can be calculated then.
+ 13 comments Java Solution
static long count(String s, long n) { long numOfS = n/s.length(); long rest = n % s.length(); if(!s.contains("a")) return 0; return s.length()>n? aCounter(s, rest) : numOfS*aCounter(s, s.length()) + aCounter(s, rest); } private static long aCounter(String s, long end) { int a=0; for (int i = 0; i < end; i++) { if (s.charAt(i) == 'a') a++; } return a; }
+ 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 }
Load more conversations
Sort 3155 Discussions, By:
Please Login in order to post a comment