Look and Say Pattern | Practice | GeeksforGeeks

Given an integer n. Return the nth row of the following look-and-say pattern.
1
11
21
1211
111221
Look-and-Say Pattern:
To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example:
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
1211 is read off as "one 1, one 2, then two 1s" or 111221.
111221 is read off as "three 1s, two 2s, then one 1" or 312211.
 

Example 1:
Input:
n = 5
Output: 111221
Explanation: The 5th row of the given pattern
will be 111221.
Example 2:
Input:
n = 3
Output: 21
Explanation: The 3rd row of the given pattern
will be 21.

Your Task:  
You dont need to read input or print anything. Complete the function lookandsay() which takes integer n as input parameter and returns a string denoting the contents of the nth row of given pattern.

Expected Time Complexity: O(2n)
Expected Auxiliary Space: O(2n-1)  

Constraints:
1 ≤ n ≤ 30
0
tirtha19025682 weeks ago
class Solution{
   static String lookandsay(int n) {
       if(n == 1) {
             return "1";
 }
 StringBuilder sb = new StringBuilder("");
 String s = "1";
 for(int i=1;i<n;i++) {
  sb = helper(s);
  s = sb.toString();
 }
 return sb.toString();
 }

static StringBuilder helper(String s) {
 StringBuilder sb = new StringBuilder("");
 
 if(s.length() == 1) {
  sb.append(1);
  sb.append(s.charAt(0));
  return sb;
 }
 
 for(int i=0;i<s.length()-1;i++) {
  int cnt = 1;
  while(i<s.length()-1 && s.charAt(i) == s.charAt(i+1)) {
   cnt++;
   i++;
  }
  sb.append(cnt);
  sb.append(s.charAt(i));
  cnt = 1;
 }
 
 if(s.charAt(s.length()-1) != s.charAt(s.length()-2) ) {
  sb.append(1);
  sb.append(s.charAt(s.length()-1));
 }
 
 return sb;
}

}

0
sanketgharatkar1231 month ago
CPP online best solution TIME:0.0/1.3 sec
    string lookandsay(int n) {       // code here              string ans="1";                            for(int i=2;i<=n;i++)       {           int count=0;           string temp_ans;           int j=0;           char temp=ans[0];           while(j<ans.size())           {               if(ans[j]==temp)               {                   count++;               }               else               {                   temp_ans.push_back(count+48);                   temp_ans.push_back(temp);                   temp=ans[j];                   count=1;               }               j++;           }                      temp_ans.push_back(count+48);           temp_ans.push_back(temp);
           ans=temp_ans;                  }                     return ans;   }      
 
0
tapanmanu20001 month ago
string lookandsay(int n) {
       if(n == 1) return "1";
       string s = "1";
       int x = s.length();
       while(--n){
           string res = "";
           for(int i = 0; i < s.length();){
               char current = s[i];
               //cout<<s[i];
               int count = 1;
               int j = i + 1;
               for(j = i + 1; (s[j] != '\0') 
               				&& (s[i] == s[j]); j++){
                   count++;
               }
               i = j;
               res.append(to_string(count));
               
               res.append(to_string(current-'0'));
               
               
           }
           s = res;
       }
       return s;
   }   
+1
kartikeyashokgautam2 months ago
Simple JAVA Solution :-
{            // for the nth number, we just need to count characters of the (n-1)th number,// for the (n-1)th number, we just need to count characters of  the (n-2)th number,// ...// hence, we get the idea of recursion here             if(n == 1) return "1";
StringBuilder res = new StringBuilder();
String s = lookandsay(n-1) + "0"; 
 
// recursively call for (n-1) th number, "0" is only for the edge case at the end of the loop with s.charAt(i+1)for(int i=0, count=1; i < s.length()-1; i++, count++){ if(s.charAt(i+1) != s.charAt(i)){  res.append(count).append(s.charAt(i));
 
 //  if next digit is different, then append the count so far  and the digit itself, then set count  to zerocount=0; }}
return res.toString();         }
0
mulangacanon2 months ago
def lookandsay(self, n):       i = 1       nterm = str()       str1 = "1"       while i < n:           nterm = self.next_number(str1)           str1 = nterm           i += 1       return str1                 def next_number(self, s):       result = []       i = 0       while i < len(s):           count = 1           while i + 1 < len(s) and s[i] == s[i + 1]:               i += 1               count += 1           result.append(str(count) + s[i])           i += 1       return "".join(result)
0
mulangacanon
This comment was deleted.
+1
dakshraghuvanshi7613 months ago
Python3 Solution (Runtime - 0.0/1.0)
 
class Solution:
    def countAndSay(self, n):
        self.n = n 
        if self.n == 1:
            return "1".format(str)

        # Calling our function one more time(recursion).
        s = self.countAndSay(self.n-1)
        s = str(s)

        # Setting the frequency(counter) = 0 and the result as empty string
        counter = 0 
        res = ""

        
        # Making groups for same consecutive numbers 
        for i in range(0 ,len(s)):
            counter += 1
            if i == len(s)-1 or s[i] != s[i+1]:
                res = res + str(counter) + s[i]
                counter = 0

        return res
 
0
rogueninjaofkonoha3 months ago
   static String lookandsay(int n) {
        //your code here
        if(n==1)
            return "1";
        else if(n==2)
            return "11";
       String s = lookandsay(n-1);
       String ans = new String();
       int count = 1;
       for(int i=0;i< s.length()-1;i++) {
           if(s.charAt(i+1) == s.charAt(i)) {
               count++;
           }
           else {
               ans = ans + count + (s.charAt(i) -'0');
               count = 1;
           }
       }
       ans = ans + count + (s.charAt(s.length()-1) -'0');
       return ans;
}
+1
ayerajkumar3 months ago
Simple Java Recursive Program
class Solution{   static String lookandsay(int n) {       String atr="";       if(n==1)       {           return "1";       }       if(n==2)       {           return "11";       }       if(n>2)       {           String str ="";           str=lookandsay(n-1);           // str="1211";           int m=str.length();           int count=1;           int i=0;           for( i=0; i<m-1; i++){               if(str.charAt(i)==str.charAt(i+1))                   count++;               if(str.charAt(i)!=str.charAt(i+1)){                   atr=atr+count+str.charAt(i);                   count=1;               }           }           atr=atr+count+str.charAt(i);       }       return atr;   }}
0
e20040806 months ago
runtime: 0.0/1.0
class Solution:
    def lookandsay(self, n):
        if n == 1:
            return '1'
        cur = None
        count = 0
        num = ''
        for digit in self.lookandsay(n - 1) + ' ':
            if digit == cur:
                count += 1
            else:
                if cur:
                    num += str(count + 1) + cur
                    count = 0
                cur = digit
        return num
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.