imashutosh51

Count and Say

Feb 27th, 2026
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. #Brute Force approach
  2. """
  3. Starting from "1", we build each term by reading the previous string and grouping consecutive identical characters.
  4. While scanning from left to right, we compare each character with its previous one; if they match we increase the count, and when they differ we append the count and the previous character to form the next sequence.
  5. """
  6. class Solution:
  7.     def countAndSay(self, n: int) -> str:
  8.         res = "1"
  9.        
  10.         for _ in range(n - 1):
  11.             temp = ""
  12.             count = 1
  13.            
  14.             for i in range(1, len(res)):
  15.                 if res[i] == res[i - 1]:
  16.                     count += 1
  17.                 else:
  18.                     temp += str(count) + res[i - 1]
  19.                     count = 1
  20.            
  21.             # Add last group
  22.             temp += str(count) + res[-1]
  23.             res = temp
  24.        
  25.         return res
Advertisement
Add Comment
Please, Sign In to add comment