Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count substrings of a given string whose anagram is a palindrome
Next article icon

Binary String of given length that without a palindrome of size 3

Last Updated : 22 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer n. Find a string of characters ‘a’ and ‘b’ such that the string doesn’t contain any palindrome of length 3.

Examples: 

Input : 3 Output : "aab" Explanation: aab is not a palindrome.  Input : 5 Output : aabba Explanation: aabba does not contain a palindrome of size 3.

The approach here is that we can use this string ‘aabb’ and print the characters of the string according to the given integer. 

We need to make sure that every third  character is different.  If we perform operation AND on i and 2 where i = 0 to any positive integer. It will generate a pattern 0, 0, 2, 2, 0, 0, 2, 2,...  0 AND 2 = 0 1 AND 2 = 0 2 AND 2 = 2 3 AND 2 = 2 4 AND 2 = 0 //repeat the pattern.

Below is the code of above approach. 

C++




// CPP program find a binary string of
// given length that doesn't contain
// a palindrome of size 3.
#include <bits/stdc++.h>
using namespace std;
 
void generatestring(int n)
{
    // Printing the character according to i
    for (int i = 0; i < n; i++)
        putchar(i & 2 ? 'b' : 'a');
    puts("");
}
 
// Driver code
int main()
{
    int n = 5;
    generatestring(n);
    n = 8;
    generatestring(n);
    n = 10;
    generatestring(n);
}
 
 

Java




// JAVA program find a binary String of
// given length that doesn't contain
// a palindrome of size 3.
 
class GFG
{
 
static void generateString(int n)
{
    String s = "";
     
    // Printing the character according to i
    for (int i = 0; i < n; i++)
        s += ((i & 2) > 1 ? 'b' : 'a');
    System.out.println(s);
}
 
// Driver code
public static void main(String[] args)
{
    int n = 5;
    generateString(n);
    n = 8;
    generateString(n);
    n = 10;
    generateString(n);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program find a binary String of
# given length that doesn't contain
# a palindrome of size 3.
def generateString(n):
    s = "";
     
    # Printing the character according to i
    for i in range(n):
        if((i & 2) > 1):
            s += 'b';
        else:
            s += 'a';
    print(s);
 
# Driver code
if __name__ == '__main__':
 
    n = 5;
    generateString(n);
    n = 8;
    generateString(n);
    n = 10;
    generateString(n);
 
# This code is contributed by 29AjayKumar
 
 

C#




// C# program find a binary String of
// given length that doesn't contain
// a palindrome of size 3.
using System;
 
class GFG
{
 
static void generateString(int n)
{
    String s = "";
     
    // Printing the character according to i
    for (int i = 0; i < n; i++)
        s += ((i & 2) > 1 ? 'b' : 'a');
    Console.WriteLine(s);
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 5;
    generateString(n);
    n = 8;
    generateString(n);
    n = 10;
    generateString(n);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// JavaScript program find a binary String of
// given length that doesn't contain
// a palindrome of size 3.
 
function generateString(n)
{
    var s = "";
     
    // Printing the character according to i
    for (var i = 0; i < n; i++)
        s += ((i & 2) > 1 ? 'b' : 'a');
    document.write(s + "<br>");
}
 
// Driver code
var n = 5;
generateString(n);
n = 8;
generateString(n);
n = 10;
generateString(n);
 
 
</script>
 
 
Output
aabba aabbaabb aabbaabbaa 


Next Article
Count substrings of a given string whose anagram is a palindrome

A

Abhishek Sharma 44
Improve
Article Tags :
  • DSA
  • Strings
  • binary-string
  • palindrome
Practice Tags :
  • palindrome
  • Strings

Similar Reads

  • Palindromic strings of length 3 possible by using characters of a given string
    Given a string S consisting of N characters, the task is to print all palindromic strings of length 3 in lexicographical order that can be formed using characters of the given string S. Examples: Input: S = "aabc"Output:abaaca Input: S = "ddadbac"Output:abaacaadadaddbddcdddd Approach: The given prob
    9 min read
  • Length of the longest substring that do not contain any palindrome
    Given a string of lowercase, find the length of the longest substring that does not contain any palindrome as a substring. Examples: Input : str = "daiict" Output : 3 dai, ict are longest substring that do not contain any palindrome as substring Input : str = "a" Output : 0 a is itself a palindrome
    6 min read
  • Check if all the palindromic sub-strings are of odd length
    Given a string 's' check if all of its palindromic sub-strings are of odd length or not. If yes then print "YES" or "NO" otherwise. Examples: Input: str = "geeksforgeeks" Output: NO Since, "ee" is a palindromic sub-string of even length. Input: str = "madamimadam" Output: YES Brute Force Approach: S
    10 min read
  • Maximize palindromic strings of length 3 possible from given count of alphabets
    Given an array arr[] of size 26, representing frequencies of character 'a' to 'z', the task is to find the maximum number of palindromic strings of length 3 that can be generated from the specified count of alphabets. Examples: Input: arr[] = {4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    9 min read
  • Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 min read
  • Print the longest palindromic prefix of a given string
    Given a string str, the task is to find the longest palindromic prefix of the given string. Examples: Input: str = "abaac" Output: aba Explanation: The longest prefix of the given string which is palindromic is "aba". Input: str = "abacabaxyz" Output: abacaba Explanation: The prefixes of the given s
    12 min read
  • Maximum length palindromic substring such that it starts and ends with given char
    Given a string str and a character ch, the task is to find the longest palindromic sub-string of str such that it starts and ends with the given character ch.Examples: Input: str = "lapqooqpqpl", ch = 'p' Output: 6 "pqooqp" is the maximum length palindromic sub-string that starts and ends with 'p'.I
    7 min read
  • Count of ways to split given string into two non-empty palindromes
    Given a string S, the task is to find the number of ways to split the given string S into two non-empty palindromic strings.Examples: Input: S = "aaaaa" Output: 4 Explanation: Possible Splits: {"a", "aaaa"}, {"aa", "aaa"}, {"aaa", "aa"}, {"aaaa", "a"}Input: S = "abacc" Output: 1 Explanation: Only po
    15+ min read
  • Count substring of Binary string such that each character belongs to a palindrome of size greater than 1
    Given binary string str, the task is to count the number of substrings of the given string str such that each character of the substring belongs to a palindromic substring of length at least 2. Examples: Input: S = "00111" Output: 6 Explanation: There are 6 such substrings in the given string such t
    6 min read
  • Maximum even length sub-string that is permutation of a palindrome
    Given string [Tex]str [/Tex], the task is to find the maximum length of the sub-string of [Tex]str [/Tex]that can be arranged into a Palindrome (i.e at least one of its permutation is a Palindrome). Note that the sub-string must be of even length. Examples: Input: str = "124565463" Output: 6 "456546
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences