Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Program to print all palindromes in a given range
Next article icon

Program to print all palindromes in a given range

Last Updated : 04 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a range of numbers, print all palindromes in the given range. For example if the given range is {10, 115}, then output should be {11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111}
We can run a loop from min to max and check every number for palindrome. If the number is a palindrome, we can simply print it. 

Implementation:

C++
#include<iostream> using namespace std;  // A function to check if n is palindrome int isPalindrome(int n) {     // Find reverse of n     int rev = 0;     for (int i = n; i > 0; i /= 10)         rev = rev*10 + i%10;      // If n and rev are same, then n is palindrome     return (n==rev); }  // prints palindrome between min and max void countPal(int min, int max) {     for (int i = min; i <= max; i++)         if (isPalindrome(i))           cout << i << " "; }  // Driver program to test above function int main() {     countPal(100, 2000);     return 0; } 
Java
// Java Program to print all  // palindromes in a given range  class GFG {          // A function to check     // if n is palindrome     static int isPalindrome(int n)     {                  // Find reverse of n         int rev = 0;         for (int i = n; i > 0; i /= 10)             rev = rev * 10 + i % 10;                      // If n and rev are same,          // then n is palindrome         return(n == rev) ? 1 : 0;     }          // prints palindrome between     // min and max     static void countPal(int min, int max)     {         for (int i = min; i <= max; i++)             if (isPalindrome(i)==1)                 System.out.print(i + " ");     }          // Driver Code     public static void main(String args[])     {         countPal(100, 2000);     } }  // This code is contributed by Taritra Saha. 
Python3
# Python3 implementation of above idea  # A function to check if n is palindrome def isPalindrome(n: int) -> bool:      # Find reverse of n     rev = 0     i = n     while i > 0:         rev = rev * 10 + i % 10         i //= 10      # If n and rev are same,      # then n is palindrome     return (n == rev)  # prints palindrome between min and max def countPal(minn: int, maxx: int) -> None:     for i in range(minn, maxx + 1):         if isPalindrome(i):             print(i, end = " ")  # Driver Code if __name__ == "__main__":     countPal(100, 2000)  # This code is contributed by # sanjeev2552 
C#
// C# Program to print all  // palindromes in a given range  using System;  class GFG {  // A function to check  // if n is palindrome  public static int isPalindrome(int n) {      // Find reverse of n      int rev = 0;     for (int i = n; i > 0; i /= 10)     {         rev = rev * 10 + i % 10;     }      // If n and rev are same,      // then n is palindrome      return (n == rev) ? 1 : 0; }  // prints palindrome between  // min and max  public static void countPal(int min,                              int max) {     for (int i = min; i <= max; i++)     {         if (isPalindrome(i) == 1)         {             Console.Write(i + " ");         }     } }  // Driver Code  public static void Main(string[] args) {     countPal(100, 2000); } }  // This code is contributed by Shrikant13 
JavaScript
<script> // A function to check if n is palindrome function isPalindrome(n) {     // Find reverse of n     var rev = 0;     for (var i = n; Math.trunc(i) > 0; i /= 10)     {         rev = ((rev*10) + (Math.trunc(i)%10));                  }        // If n and rev are same, then n is palindrome     return (n==rev); }       // prints palindrome between min and max function countPal(min,  max) {     for (var i = min; i <=max; i++)     {         if(isPalindrome(i))         document.write(i+" " );        } }  // Driver program to test above function      countPal(100, 2000); </script>      

Output
101 111 121 131 141 151 161 171 181 191 202 212 222 232 242  252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404   414 424 434 444 454 464 474 484 494 505 515 525 535 545 555 565   575 585 595 606 616 626 636 646 656 666 676 686 696 707 717 727   737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888  898 909 919 929 939 949 959 969 979 989 999 1001 1111 1221 1331   1441 1551 1661 1771 1881 1991 

Time Complexity:

Time complexity of function to check if a number N is palindrome or not is O(logN).

We are calling this function each time while iterating from min to max.

So the time complexity will be O(Dlog(M)).

Where,

D= max-min

M = max

Auxiliary Space: O(1)

Approach#2: Using filter

This approach defines a function is_palindrome that checks if a given number is a palindrome. It then defines a function palindrome_range that takes a range of numbers and returns a list of all palindromic numbers in that range using a combination of the range, filter, and list functions.

Algorithm

1. Define a function that takes two integer arguments as the range of numbers to check for palindromes.
2. Create a list of all integers in the range.
3. Use map and lambda to filter the list to only include palindromes.
4. Return the list of palindromes.

C++
#include <iostream> #include <sstream> #include <vector>  // Function to check if a number is a palindrome bool isPalindrome(int num) {     // Convert integer to string and compare it with its     // reverse to check for palindrome     std::string numStr = std::to_string(num);     return numStr            == std::string(numStr.rbegin(), numStr.rend()); }  // Function to find palindromes in a given range std::vector<int> palindromeRange(int start, int end) {     // Create a vector of numbers in the specified range     std::vector<int> nums;     for (int i = start; i <= end; i++) {         nums.push_back(i);     }      // Vector to store palindromes found in the range     std::vector<int> palindromes;     for (int x : nums) {         // Check if the number is a palindrome and add it to         // the palindromes vector         if (isPalindrome(x)) {             palindromes.push_back(x);         }     }      return palindromes; }  // Main method int main() {     int start = 100;     int end = 2000;      // Find palindromes in the given range and print the     // result     std::vector<int> result = palindromeRange(start, end);      // Print the result     std::cout << "[";     for (size_t i = 0; i < result.size(); ++i) {         std::cout << result[i];         if (i < result.size() - 1) {             std::cout << ", ";         }     }     std::cout << "]" << std::endl;      return 0; } 
Java
import java.util.ArrayList; import java.util.List;  public class Main {     // Function to check if a number is a palindrome     static boolean isPalindrome(int num) {         // Convert integer to string and compare it with its reverse to check for palindrome         String numStr = Integer.toString(num);         return numStr.equals(new StringBuilder(numStr).reverse().toString());     }      // Function to find palindromes in a given range     static List<Integer> palindromeRange(int start, int end) {         // Create a list of numbers in the specified range         List<Integer> nums = new ArrayList<>();         for (int i = start; i <= end; i++) {             nums.add(i);         }          // List to store palindromes found in the range         List<Integer> palindromes = new ArrayList<>();         for (int x : nums) {             // Check if the number is a palindrome and add it to the palindromes list             if (isPalindrome(x)) {                 palindromes.add(x);             }         }          return palindromes;     }      // Main method     public static void main(String[] args) {         int start = 100;         int end = 2000;          // Find palindromes in the given range and print the result         List<Integer> result = palindromeRange(start, end);         System.out.println(result);     } } 
Python3
def is_palindrome(num):     return str(num) == str(num)[::-1]  def palindrome_range(start, end):     nums = list(range(start, end+1))     palindromes = list(filter(lambda x: is_palindrome(x), nums))     return palindromes  start=100 end=2000 print(palindrome_range(start, end)) 
C#
using System; using System.Collections.Generic; using System.Linq;  class Program {     // Function to check if a number is a palindrome     static bool IsPalindrome(int num)     {         // Convert integer to string and compare it with its         // reverse to check for palindrome         string numStr = num.ToString();         return numStr             == new string(numStr.Reverse().ToArray());     }      // Function to find palindromes in a given range     static List<int> PalindromeRange(int start, int end)     {         // Create a list of numbers in the specified range         List<int> nums             = Enumerable.Range(start, end - start + 1)                   .ToList();          // List to store palindromes found in the range         List<int> palindromes = new List<int>();         foreach(int x in nums)         {             // Check if the number is a palindrome and add             // it to the palindromes list             if (IsPalindrome(x)) {                 palindromes.Add(x);             }         }          return palindromes;     }      // Main method     static void Main()     {         int start = 100;         int end = 2000;          // Find palindromes in the given range and print the         // result         List<int> result = PalindromeRange(start, end);          // Print the result         Console.Write("[");         for (int i = 0; i < result.Count; ++i) {             Console.Write(result[i]);             if (i < result.Count - 1) {                 Console.Write(", ");             }         }         Console.WriteLine("]");     } } 
JavaScript
// This function checks whether a given number is a palindrome or not function is_palindrome(num) {     return String(num) === String(num).split("").reverse().join(""); }  // This function returns a list of all palindrome numbers within a given range function palindrome_range(start, end) {     let nums = Array.from({length: (end - start) + 1}, (_, i) => i + start);     let palindromes = nums.filter(num => is_palindrome(num));     return palindromes; }  // Example usage let start = 100; let end = 2000; console.log(palindrome_range(start, end)); 

Output
[101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999, 1001, 1111, 1221, 1331, 1441, 1551, 1661, 1771, 1881, 1991]

Time complexity: O(n*k), where n is the number of integers in the range and k is the length of the largest integer in the range.

Auxiliary Space: O(m), where m is the number of palindromes in the range


Next Article
Program to print all palindromes in a given range

K

kartik
Improve
Article Tags :
  • Strings
  • DSA
  • palindrome
Practice Tags :
  • palindrome
  • Strings

Similar Reads

    Palindrome String Coding Problems
    A string is called a palindrome if the reverse of the string is the same as the original one.Example: “madam”, “racecar”, “12321”.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
    2 min read
    Palindrome String
    Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
    13 min read

    Check Palindrome by Different Language

    Program to Check Palindrome Number in C
    Palindrome numbers are those numbers that remain the same even after reversing the order of their digits. In this article, we will learn how to check whether the given number is a palindrome number using C program.ExamplesInput: 121Output: YesExplanation: The number 121 remains the same when its dig
    3 min read
    C Program to Check for Palindrome String
    A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.The simplest method to check for palindrome string is to reverse the given string and store it in a temp
    4 min read
    C++ Program to Check if a Given String is Palindrome or Not
    A string is said to be palindrome if the reverse of the string is the same as the original string. In this article, we will check whether the given string is palindrome or not in C++.ExamplesInput: str = "ABCDCBA"Output: "ABCDCBA" is palindromeExplanation: Reverse of the string str is "ABCDCBA". So,
    4 min read
    Java Program to Check Whether a String is a Palindrome
    A string in Java can be called a palindrome if we read it from forward or backward, it appears the same or in other words, we can say if we reverse a string and it is identical to the original string for example we have a string s = "jahaj " and when we reverse it s = "jahaj"(reversed) so they look
    8 min read

    Easy Problems on Palindrome

    Sentence Palindrome
    Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
    9 min read
    Check if actual binary representation of a number is palindrome
    Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
    6 min read
    Print longest palindrome word in a sentence
    Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
    14 min read
    Count palindrome words in a sentence
    Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
    5 min read
    Check if characters of a given string can be rearranged to form a palindrome
    Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
    14 min read
    Lexicographically first palindromic string
    Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
    13 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