Adsense 728 * 15

Search

Custom Search

Java Program to Find First Non-Repeating Character in a String

Write a Java program to Find first non-repeated character in a String. Suppose, a user has input AABCDEBFCH now the first non-repeated character in this string is D.

Input     - AABCDEBFCH
Output  - D

Java Programs for practice

C, C++ Program to print first non-repeating character of a string

How to Print First Non-repeated Character of a String

i) Method 1 - Naive Approach

Use two for loops and compare a character with each character of a string. The time complexity for this approach is O(n2).

 for(int i = 0; i < len; i++) {
  
     flag = 0; 
  
     for(int j = 0; j < len; j++) {
   
        /* If it's equal and indexes
           is not same */
        if((str[i] == str[j]) && (i != j)) {
             flag = 1;
             break;
        }
     }

ii) Method 2 - Use hash map to create a key and value pair of character and it's count. This approach is much better as compared to first one.

Traverse a string and create a hash table for character and it's count. If there  is no value stored for a character then set it to 1. Else we increment the character value by 1.

Explanation -



Let's implement a hash map to solve this problem.

Java Program to Find First Non-repeating Character in a String


import java.util.*;

public class FirstNonRepeatedCharacter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        System.out.println("Please enter an input string ");
        
        // Take a input

        Scanner in = new Scanner(System.in);
        
        //Assign value into str

        String str = in.nextLine();
        
        // Length of a string

        int len = str.length();
        
        // Using HashMap

        HashMap<Character, Integer> charcount 
                  = new HashMap<Character, Integer>();
        
        Character ch;
        
        /*Traverse a string and create a hash table for 
          character and it's count. 
          If there  is no value stored for a character then set it to 1. 
          Else we increment the character value by 1 */

        for(int i = 0; i < len; i++) {
            
            ch = str.charAt(i);
            
            /* If character is already exists 
               then increment it's count by 1 */

            if(charcount.containsKey(ch)) {
                
                charcount.put(ch, charcount.get(ch)+1);
                
            } else {
                
                // If character is not exist

                charcount.put(ch, 1);
            }
        }
        
        for (int j = 0; j < len; j++) {
            
            ch = str.charAt(j);
            
            if(charcount.get(ch) == 1){
                
                System.out.println("First non-repeated character 
                                    is " + ch);
                break;
                
            }
        }
    }
    
}



Output -

Please enter an input string AABCDEBFCH

First non-repeated character is D

Java Programming Books

C, C++ Program to Check whether a String is Palindrome or not

Write a C, C++ program to check whether a string is palindrome or not. Given an input string, we have to write a code to check whether a input string is palindrome or not. 

Program to check whether a number is palindrome or not

Programming questions on strings

what is Palindrome ?

Palindrome is a word, phrase, or sequence that reads the same backwards as forwards.

For example - Nitin, Madam etc. If you reverse word Madam it's still remains the same.



Algorithm to Check whether String is Palindrome or not

Traverse a string from both the ends and compare if char on both the indexes are equal. If character on both the indexes are equal then it's a palindrome.  Let's implement it.

1. Take two indexes.

     int start = 0;
     int end = strlen - 1;


2. Traverse a string from both the ends and compare. If  start and end indexes of a string is  equal then it's a palindrome.






Program to Check Whether a String is Palindrome in C

#include <stdio.h>
#include <string.h>

int main()
{
   char str[100];
   
   /* Take input string from user. */

   printf("Enter a string");
   gets(str);
   
   int start=0,flag=0;
   int end = strlen(str)-1;
   
   /* start index is less than end index. */
   
   while(start < end){
       
       /* If start and end char is equal. */
       
       if(str[start]==str[end]){
           
           flag=1;
           
       }else {
           
           flag=0;
           break;
       }
       
       start++;
       end--;
   }
   
   if(flag){ 

       printf("String is a palindrome");
   
   }else{

       printf("String is not a palindrome");
   }
   
    return 0;
}



Output:

Enter a string :  Rar

String is a palindrome

Program to Check whether a String is Palindrome or not in C++


#include <iostream>
#include <string.h>

using namespace std;

int main() {

    /* String declaration */

    char str[100];

    int start, end, flag = 1;

    /* Take input string from a user */

    cout << "Please enter a string ";
    cin >> str;

    // Assign the value of two indexes
    
    start = 0;
    end   = strlen(str) - 1;

    /* start index is less than end index. */

    while (start < end) {

        /* If start and end char of a string
           is not equal then break a loop */

        if (str[start] != str[end]) {

            flag = 0;
            break;

        }

        start++;
        end--;
    }

    if (flag) {

        cout << "Input string is a palindrome";

    } else {

        cout << "Input string is not a palindrome";

    }

    return 0;
}


Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

C, C++ Program to Insert an Element in an Array

Write a C, C++ program to insert an element in an array. In this program, we have to insert a new element at in an array.

Let's take an example -

Input array - {4, 3, 1, 5}

Input position - 3

New element - 7

After inserting an element - {4, 3, 1, 7, 5}

Program to delete an element from an array

Programming questions on Arrays

Program to print smallest element of an array


Logic of a Inserting an Element in an Array

i) Take a position and new element as an input.

ii) Move an existing element one position up until  the position is reached where a new element is need to be inserted.


C Program to Insert an Element in an Array


#include <stdio.h>

int main(void) {
 
 int arr[100], size, pos, val, i, temp;
 
 printf("Enter the size of an array (MAX 100) \n");
 scanf("%d", &size);
 
 // Create an input array

 printf("Enter an elements in an array \n");
 
 for(i = 0; i < size; i++) {
    scanf("%d", &arr[i]);
 }
 
 // Take a position of a new element

 printf("Enter a position( To insert a new element in an array)\n");
 scanf("%d", &pos);
 
 printf("Enter a value to insert\n");
 scanf("%d", &val);
 
 //Shift element by one position
 
 for(i = size; i >= pos; i--) {
  
  arr[i] = arr[i-1];
  
 }
 
 //Increase the length of an array

 size++;
 
 //Insert new value in an array

 arr[pos] = val;
 
 printf("Array after inserting a new value");
 
 for(i = 0; i < size; i++) {
  printf(" %d ", arr[i]);
 }
 
 return 0;
}


C++ Program to Insert an Element in an Array


#include <iostream>
using namespace std;

 int main() {
 
 int arr[100], size, pos, val, i, temp;
 
 cout << "Enter the size of an array (MAX 100) \n";
 cin  >> size;
 
 // Create an input array
 
 cout << "Enter an elements in an array \n";
 
 for(i = 0; i < size; i++) {
  cin >> arr[i];
 }
 
 // Take a position of a new element
 cout << "Enter a position( To insert a new element in an array)\n";
 cin  >> pos;
 
 cout << "Enter a value to insert\n";
 cin  >> val;
 
 //Shift element by one position
 
 for(i = size; i >= pos; i--) {
  
  arr[i] = arr[i-1];
  
 }
 
 //Increase the length of an array
 size++;
 
 //Insert new value in an array
 arr[pos] = val;
 
 printf("Array after inserting a new value");
 
 for(i = 0; i < size; i++) {
  cout << arr[i] << " ";
 }
 
 
 return 0;
 }



Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

Program to Reverse a Number in C, C++

Write a C, C++ program to reverse a number. In this program, A number is input by a user and our code will reverse this number. For reversing a number we'll use iterative approach.


Reverse a number using Recursion


How to Reverse a Number

Let's check the logic.

1. Take a input from user.

2.
 while(num!=0) {

          temp = num%10;   // Store the result in temp variable

          rev = (rev*10)+temp;

          num = num/10; 
        
      }
 

How this code is working 


 Suppose, A input number is 243. 

 While loop condition is true, as num is 243 

 rev = 0 * 10 + 3; 
 num = 24; 

 Now num is 24 still while loop condition is true, 

 rev = 3*10 + 4; 
 num = 2; 

 Now num is 2, again while loop is executed, 

 rev = 34 * 10 + 2 
 num = 0; 

 Now number is zero while loop will break


Program to Reverse a String


C++ Program to Reverse a Number



 #include<iostream>
  using namespace std;

  int main()
  {
     int num,temp,rev=0;

     cout << "Enter a number \n";
     cin  >> num;

 
     while(num != 0){

       temp = num%10;
       rev  = (rev*10) + temp;
       num  = num/10;

     }

     cout<<"\n Reverse of a input number is "<< rev;

     return 0;

 }




Output -

Enter a number   243

Reverse of a input number is   342

C Program to Reverse a Number


#include <stdio.h>

int main(void) {
 
    int num, temp, rev=0;

    printf("Enter a number");
    scanf("%d", &num);

 
    while(num != 0){

       temp = num % 10;
       rev  = (rev*10)+temp;
       num  = num/10;

    }

    printf("Reverse of a input number is  %d", rev);


    return 0;
}



Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books



Program to Reverse Words in a String - C, C++ Code

Write a C, C++ program to reverse words in a given string. Given an input string, we have to write a code to reverse words of a string.

Programming questions on strings

Suppose, An input string is learn programming.

Input    - learn programming
Output - nrael gnimmargorp

C Program to Reverse Words in a String


#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
 
   // String declaration of max size 100
   char str[100], temp;
   int len, i, j, k;
 
   // Input string
   printf("Enter a string \n");
   gets(str);
 
   len = strlen(str);
 
   for(i = 0, j = 0; i < len; i++) {
  
      // If it's not a alphabet or number 
      if(!isalnum(str[i]) || (i == len - 1)) {
   
        if (i < len - 1) {
            k = i - 1;
        } else {
            k = i;
        }
   
        //Reverse
        while(k > j) {
           temp   = str[j];
           str[j] = str[k];
           str[k] = temp;
           k--;
           j++;
       }
   
       j = i + 1;
    }
  }
 
  printf("%s", str);
 
  return 0;
}



C++ Program to Reverse Words in a String


#include <iostream>
#include <string.h>

using namespace std;

int main() {
 
   char str[100], temp;
   int i, j, k, len;
 
   cout << "Enter a string \n";
   cin.getline(str,100);
 
   len = strlen(str);
 
   for(i = 0, j =0; i < len; i++) {
  
     if(str[i]==' ' || i == len-1){
   
        if(i < len-1) {
           k = i - 1;
        } else {
           k = i;
        }
  
        while (k > j) {
         temp   = str[j];
         str[j] = str[k];
         str[k] = temp;
         j++;
         k--;
      }
  
      j = i + 1;
    }
  }
 
  cout << str;
 
  return 0;
}

Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

Check whether two Strings are Anagram of each other - C, C++ Code

Write a C, C++ program to check whether two strings are anagram of each other.  Before solving this problem, let's first understand what is anagram.

What is Anagram

Two strings are said to be anagram, If both strings contain same characters, only the order of characters can be different.

For example -

i) "raj" and "jar" are anagram of each other.

ii) "abcde" and "dbaec" are anagram of each other.

Programming questions on strings

How to Check whether two Strings are Anagram of each other

Method 1

Use sorting to sort both the strings and then compare. If both the strings are same then it's a anagram

Quicksort program in C, C++

Sorting algorithm and their time complexity

Method 2

Create hash and compare.

Anagram Program in C


#include <stdio.h>
#include <string.h>

/* Check if both strings are anagrams */

int isAnagram(char str1[], char str2[]) {
 
      /* Default value assigned to zero */

      char str[256] = { 0 };
 
      /* Increment character count based on first string */

      for (int i = 0; i < strlen(str1); i++ ) {
  
           str[str1[i]]++;
      }
 
      /* Decrement character count based on second string */

      for (int j = 0; j < strlen(str2); j++ ) {
  
           str[str2[j]]--;
  
      }
 
        /* If both strings are anagrams 
           then net character count is zero */

      for (int k = 0; k < 256; k++ ) {

           if (str[k] != 0) {
    
               return 0;
           }
  
       }
 
      return 1;
}

int main(void) {

   char str1[100], str2[100];
 
   printf("\n Enter first string");
   gets(str1);
 
   printf("\n Enter second string");
   gets(str2);
 
   if (isAnagram(str1, str2)) {
  
      printf ("\n Enter strings are anagrams");
  
   } else {
  
     printf ("\n Enter strings are not anagrams");
   }
 
   return 0;
}



Output :

Enter first string  :  raj

Enter second string : jar

Enter strings are anagrams


Programming questions on Strings

Programming questions on Recursion

Programming questions on Array

Programming questions on Linked List

Program to Print First Non Repeating Character of a String - C, C++ Code

Write a C, C++ program to print first non repeating character of a string.  Given an input string, write a code to print only first non-repeating character of a string.

Programming questions on string.

Let's take an example. Suppose an input string is HELLO.  In this word, H is a first non-repeating character.

Method 1 - Using two for loops to compare each character of a string with other characters. The time complexity of this approach is O(n2).

C Program to Find First Non Repeating Character of a String


#include <stdio.h>
#include <string.h>

int main(void) {
 
 char str[100] = "cprogrammingcode";
 int len  = strlen(str);
 int flag;
 
 /* Two loops to compare each
    character with other character
    */
 for(int i = 0; i < len; i++) {
  
     flag = 0; 
  
     for(int j = 0; j < len; j++) {
   
        /* If it's equal and indexes
           is not same */
        if((str[i] == str[j]) && (i != j)) {
             flag = 1;
             break;
        }
     }
  
      if (flag == 0) {
          printf("First non-repeating character is %c",str[i]);
          break;
      }
  
 }
 
 if (flag == 1) {
     printf("Didn't find any non-repeating character");
 }
 
  return 0;
}



Now let's optimize this solution .

Method 2 - Using hash map library in C++.

C++ Program to Find First Non Repeating Character in a String

#include <iostream>
#include <map>
#include <string.h>
using namespace std;

int main() {
    char str[100] = "cprogrammingcode";
    int i,len;


    /* Declare hash */
    map<char,int> hash;
    len = strlen(str);
   
   /* Make key and value pair
      key denotes character
      value is the count of a character
   */
   for(i = 0; i < len; i++){

      hash[str[i]]= hash[str[i]] + 1;
  
   }
  
  
    /* Check the count
      if count is 1 then print the element 
    */
   for(j=0;j<len;j++){
 
       if (hash[str[j]]==1){
          cout<<"First non-repeated character is "<<str[j];
          break;
       } 
   }

   return 0;
}


Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

Program to Print Duplicate Element of an Array - C, C++ Code

Write a C, C++ program to print a duplicate element of an array. Given an array, Only one element in an array is repeated, print a duplicate element.

C, C++ Interview Questions


Method 1 - Naive Approach

Use two for loops, Compare each element of an array with other element. The time complexity of this approach is  O(n2).

C Program to Print Duplicate Element in an Array



 #include <stdio.h>

  int main(void) {
 
     int arr[100], i, j, size;
   
     printf("Enter the size of an array \n");
     scanf("%d",&size);
   
     printf("Enter the elements in an array\n");
   
     for( i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
     }
  
     /* Logic to print duplicate
        element of an array */
      
      for(i = 0; i < size; i++){
         for(j=i+1; j < size; j++){
   
           if(arr[i] == arr[j]){
    
              printf("Duplicate element in an array is %d ",arr[i]);
              break;
            }
         }
      }
    
      return 0;
 }


Output -

Enter the size of an array   5

Enter the elements in an array  2   3   6   5   3

Duplicate element in an array is  5



Method 2 - Use hashing

In this approach, We are using C++ map library. The time complexity of this program is O(n).


C ++ code to Find Duplicate Element in Array



#include <iostream>
#include <map>

using namespace std;

int main() {
 
   int arr[100], i, size;
   
   cout <<"Enter the size of an array\n";
   cin  >> size;
   
   cout <<"Enter elements in an array \n";
   
   for(i = 0; i < size; i++) {
       cin >> arr[i];
   }

    // Map STL library implementation
    map<int, int> hash;
   
   
   /* Make key and value pair.
      key denotes the element
      value is the count of that element.
   */ 
    for(i = 0; i < size; i++) {
      hash[arr[i]] = hash[arr[i]] + 1;  
    }
  
  
   /* Check the count and if 
      count is greater than 1 then 
      print the element */

    for(i = 0; i < size; i++){

        if (hash[arr[i]] > 1){
          cout<<"Repeated element is "<< arr[i];
          break;
        }
    }
    
    return 0;
}


Programming questions on strings

Sorting algorithm and their implementation

Search algorithm

Question on arrays

Program to Delete an Element from an Array - C, C++ Question

Write a C, C++ program to delete an element from an array.  Given an array, Write a code to delete an element from a position input by a user.

To solve this problem, let's first understand what is the input parameter and what's our approach to solve this problem.

In this program, we take an array and position of an element to delete.


Delete Duplicate element in an Array.

Reverse an Array using Recursion.


C++ Program to Delete an Element form an Array



#include <iostream>
using namespace std;

int main() {
 
   
   int a[100], size, pos, i, count = 0;

   cout << "Enter the size of an array \n";
   cin  >> size;
   
   cout << "Enter the value in an array \n";
   
   // Take an input array
   for (i = 0; i < size; i++) {
    cin >> a[i];
   }
   
   //Input position where we delete an element 
   cout << "Enter the position \n";
   cin  >> pos;

  // Traverse till the position of an element
  while(count != pos)   
    count++;

  // Shift by one element
  while(count < size) {
 
     a[count] = a[count+1];
     count++;
   }

   // Reduce the size of an array
   size--;            

  // Print an array after deleting an element
  for(i = 0; i < size; i++) {
   
    cout<<"   "<<a[i];
    
  }

  return 0;
}


Output : 

Enter the size of an array  - 5

Enter the value in an array

2     4     6     1      2

Enter the position    -   2

 2    4   1    2



C Program to Delete an Element from an Array

 #include <stdio.h>

int main() {
 
    /* Let's say you have an array. */
 
    int arr[]={3,1,6,7,2,9,8};
 
   /* You want to delete element on 2nd index which is 6. */
 
   int delindex = 2;
 
   /* Array size. */
 
   int size = 7;
 
   int i;
 
   for(i = delindex; i < size-1; i++){
  
      arr[i]=arr[i+1];
   }
 
 
   /* After deletion the array is. */
 
   for(i=0;i<size-1;i++){
  
          printf("%d ",arr[i]);
    }
    return 0;
}




Output:

3   1   7    2    9     8


Programming questions on Strings

Programming questions on Recursion

Programming questions on Array

Programming questions on Linked List

Binary Search Program in C, C++

Write a C, C++ program to implement a binary search. Binary search is an efficient search algorithm as compared to linear search.  Let's implement this algorithm in  C, C++.

Binary Search


Binary search is a search algorithm that finds the position of an element (target value) within a sorted array. It is also known as half-interval search or logarithmic search.

Important Points

i) Always use binary search with sorted values (either in asc or desc order).

Bubble sort algorithm and their implementation

Quicksort algorithm and their implementation

ii) Time complexity of binary search.

      Best case performance - O(1)

      Average and worst case time complexity - O(nlogn)


Binary Search using Recursion in C, C++

Sorting algorithm and their time complexity

Binary Search Algorithm


    low = 0;
    high = size - 1;
    
    while (low <= high) {
     
        /* Calculate mid index */

        mid = (low + high) / 2;
    
        /* If element is found at mid index
           then return the index */

        if (arr[mid] == num ) {
         
            return mid+1;
         
        } else if ( arr[mid] > num) {
         
            high = mid - 1;
         
        } else if ( arr[mid] < num) {
         
            low = mid + 1;
         
        }
    }

    /* If element is not found return -1 */

    return -1;
  

Binary Search Program in C++


#include<iostream.h>
#include<conio.h>

void main()
{

   int arr[100],beg,mid,end,i,n,num;

   cout << "\n Enter the size of an array ";
   cin >> n;

   cout << "\n Enter the values in sorted order (asc or desc) \n";

   for(i = 0; i < n;i++)
   {   
       cin >> arr[i];
   }   

  
   /* Initialize beg and end value. */

   beg = 0;
   end = n-1;

   cout << "\n Enter a value to be searched in an array ";
   cin >> num;

   /* Run loop, while beg is less than end. */

   while( beg <= end)
   {   
       
      /* Calculate mid. */
        
      mid = (beg+end)/2;

     /* If value is found at mid index,
        the print the position and exit. */

      if(arr[mid] == num)
      {   
         cout << "\nItem found at position "<< (mid+1);
   
          exit(0);

      } else if(num > arr[mid]) {

         beg=mid+1;

      } else if (num < arr[mid]) {

         end=mid-1;
 
      }

   }

    cout << "Number does not found.";
 }

Output:

Enter the size of an array : 7

Enter the values in sorted order (asc or desc) :

3    5    6    8   9   12  13

Enter a value to be search :  6

Item found at position : 3

Binary Search Program in C


#include <stdio.h>

/* Search number in an array using binary search algorithm */

int binarySearch (int arr[], int num, int size) {

    int low, high, mid;
    
    low = 0;
    high = size - 1;
    
    while (low <= high) {
     
        /* Calculate mid index */

        mid = (low + high) / 2;
    
        /* If element is found at mid index 
           then return the index */

        if (arr[mid] == num ) {
         
            return mid+1;
         
        } else if ( arr[mid] > num) {
         
            high = mid - 1;
         
        } else if ( arr[mid] < num) {
         
            low = mid + 1;
         
        }
    }
    
    return -1;
 
}

int main(void) {
    
   int arr[100], len, num, result;
 
   printf(" \n Enter the size of an array (Max 100)");
   scanf ("%d", &len);
 
   printf("\n Enter the elements of an array in asc or desc order");
 
   /* Taking array input values from user */
 
   for (int i = 0; i < len; i++) {
  
      scanf ("%d", &arr[i]);
  
   }
 
   printf ("\n Enter the elements to be searched in an array");
   scanf ("%d", &num);
 
   result = binarySearch (arr, num, len);
 
   if (result == -1) {
  
       printf (" \n Number is not found in an array");
  
   } else {
  
       printf (" \n Number is found at %d position", result );
   }
 
   return 0;
}

Output :

Enter the size of an array (Max 100) : 5

Enter the elements of an array in asc or desc order : 2   3    6   7   8

Enter the elements to be searched in an array : 7

Number is found at 4 position


Programming questions on Strings

Programming questions on Recursion

Programming questions on Array

Programming questions on Linked List