coding (1)
coding (1)
int fibonacci(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 10; // Number of terms in the Fibonacci series you
want to print
cout << "Fibonacci series up to " << n << " terms: ";
return 0;
}
Coding
###Substring Match
# Example usage
if __name__ == "__main__":
big_string = input("Enter the big string: ")
sub_string = input("Enter the substring: ")
if result != -1:
print(f"Substring found at index: {result}")
else:
print("Substring not found.")
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
for (int i = 1; i <= 100; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
return 0;
}
// Driver code
int main()
{
int num = 5;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
int main() {
char str[100];
int len;
bool flag = false;
len = strlen(str);
if(flag) {
cout << str << " is not a palindrome." << endl;
} else {
cout << str << " is a palindrome." << endl;
}
return 0;
}
####FIND Duplicates in array
\def find_duplicates(arr):
counts = {}
duplicates = []
return duplicates
# Example usage
arr = [1, 2, 3, 2, 4, 5, 1]
print("Duplicates:", find_duplicates(arr)) # Output: [1, 2]
###Remove Duplicates
def remove_duplicates_preserve_order(arr):
unique_elements = []
for num in arr:
if num not in unique_elements:
unique_elements.append(num)
return unique_elements
# Example usage
arr = [1, 2, 3, 2, 4, 5, 1]
print("Array without duplicates (order preserved):",
remove_duplicates_preserve_order(arr)) # Output: [1, 2, 3, 4,
5]
do
{
digit=num%10;
rev=(rev*10)+digit;
num=num/10;
}
while(num!=0);
if(n==rev &&n>0)
cout<<"number is palindrom"<<endl;
else
cout<<"not palindrom"<<endl;
return 0;
# Example usage
strings = ["apple", "banana", "grape",
"kiwi"]
min_length = 6
result =
filter_strings_by_length(strings,
min_length)
print(result) # Output: ["banana"]
def is_isogram(word):
word = word.lower() # To handle case sensitivity
return len(word) == len(set(word))
# Example usage
print(is_isogram("Ambidextrously")) # Output: True
(Isogram)
print(is_isogram("Mississippi")) # Output: False (Not an
isogram)
int fibonacci(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 100; // Number of terms in the Fibonacci series you
want to print
cout << "Fibonacci series up to " << n << " terms: ";
return 0;
}
###Reverse a String
function reverseString(str) {
return str.split("").reverse().join("");
}
// Example usage
const str = "Hello, World!";
console.log(reverseString(str)); // Output: "!dlroW ,olleH"
int main() {
string input;
cout << "Enter a string: ";
getline(cin, input); // To read the entire line of input
int vowelCount = countVowels(input);
cout << "Number of vowels: " << vowelCount << endl;
return 0;
#include <iostream>
using namespace std;
int main() {
// declaring string
string sentence = "Mary had a little lamb";
// initialising no of words to 0
int words = 0;
// store length of string in lenOfSentence
int lenOfSentence = sentence.size();
}
// at the end of the for loop, no. of spaces have been
// counted. Increment word count one more time to get
// no. of words
words = words + 1;
return longestLength;
}
int main() {
string input;
cout << "Enter a sentence: ";
getline(cin, input); // Use getline to read the entire sentence
1. Reverse a String
Solution:
cpp
Copy code
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
cout << "Reversed String: " << reverseString(str)
<< endl;
return 0;
}
Solution:
cpp
Copy code
#include <iostream>
#include <string>
using namespace std;
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "aaabbc";
cout << "Compressed String: " << compressString(str) <<
endl; // Output: a3b2c1
return 0;
}
Given a string s, find the length of the longest substring without repeating
characters.
Example
● Input: s = "abcabcbb"
● Output: 3
Explanation: The answer is "abc", with a length of 3.
● Input: s = "bbbbb"
● Output: 1
Explanation: The answer is "b", with a length of 1.
#include <iostream>
#include <string>
using namespace std;
int lengthOfLongestSubstring(string s) {
int lastIndex[256] = {0}; // Array to
store the last index of each character
int maxLength = 0;
int left = 0; // Left pointer of the
sliding window
return maxLength;
}
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
int result =
lengthOfLongestSubstring(input);
cout << "Length of the longest
substring without repeating characters: "
<< result << endl;
return 0;
}
#include <iostream>
#include <string>
int lengthOfLongestSubstring(string s) {
int lastIndex[256] = {0}; // Array to store the last index of each character
int maxLength = 0;
● lastIndex[256] = {0}: This array will store the last seen position
of each character. Initially, all values are set to 0, meaning no characters
have been seen.
● maxLength = 0: Stores the maximum length of any substring without
repeating characters found so far.
● left = 0: Marks the start of the "sliding window" — it will adjust as
we find repeating characters.
// Update the left pointer if the character has been seen and is in the
current window
left = lastIndex[s[right]];
}
Adjust the left Pointer: If a repeating character is found, we slide the left
pointer to lastIndex[currentChar]. This removes the repeated character
from the window, so the substring starting at left and ending at right no
longer has duplicates.
}
Calculate the Length of the Current Window: The length of the current
substring is right - left + 1.
return maxLength;
int main() {
string input;
cout << "Length of the longest substring without repeating characters: "
<< result << endl;
return 0;
}
1. Check for Repeating Character:
○ lastIndex['a'] is 0, which is not greater than left = 0,
meaning 'a' hasn’t been seen within the current window.
2. Update lastIndex:
○ Set lastIndex['a'] = right + 1 = 1.
3. Update maxLength:
○ Calculate maxLength = max(0, right - left + 1) =
max(0, 0 - 0 + 1) = 1.
4. Current substring: "a", maxLength = 1.
int main(){
string str;
cin>>str;
int len, i;
bool isPalindrome = true;
len = str.length();
for(i=0; i<len/2; i++){
if(str[i] != str[len-1-i]){
isPalindrome = false;
break;
}
}
if(isPalindrome){
cout<<"Yes"<<endl;
} else {
cout<<"NO"<<endl;
}
return 0;
}
int main(){
int num;
cin>>num;
string str = to_string(num);
int len, i;
bool isPalindrome = true;
len = str.length();
for(i=0; i<len/2; i++){
if(str[i] != str[len-1-i]){
isPalindrome = false;
break;
}
}
if(isPalindrome){
cout<<"Yes"<<endl;
} else {
cout<<"NO"<<endl;
}
return 0;
}
1. Bubble Sort
Bubble Sort repeatedly compares and swaps adjacent
elements if they are in the wrong order.
python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
# Swap if the element found is greater than the next
element
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Sorted array:", bubble_sort(arr))
2. Selection Sort
# Example usage
arr = [64, 25, 12, 22, 11]
print("Sorted array:", selection_sort(arr))
3. Insertion Sort
# Example usage
arr = [12, 11, 13, 5, 6]
print("Sorted array:", insertion_sort(arr))
4. Merge Sort
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
print("Sorted array:", merge_sort(arr))
python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
# Swap if the element found is greater than the next
element
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Sorted array:", bubble_sort(arr))
2. Selection Sort
python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
# Example usage
arr = [64, 25, 12, 22, 11]
print("Sorted array:", selection_sort(arr))
3. Insertion Sort
Insertion Sort builds the sorted array one item at a time by
inserting elements into their correct positions.
python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# Example usage
arr = [12, 11, 13, 5, 6]
print("Sorted array:", insertion_sort(arr))
4. Merge Sort
python
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
print("Sorted array:", merge_sort(arr))
5. Quick Sort
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Example usage
arr = [3, 6, 8, 10, 1, 2, 1]
print("Sorted array:", quick_sort(arr))
// Sort array of string in C++
#include<bits/stdc++.h>
using namespace std;
void bubblesort(vector<string>& arr){
int n = arr.size();
string temp;
for(int i=0; i<n-1; i++){
for(int j=0; j<n-i-1; j++){
if(arr[j+1]< arr[j]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main(){
vector<string>words = {"banana", "apple", "grape", "berry"};
bubblesort(words);
ChatGPT
You said:
give string realted and all others c++ prioblem with solutiuon for problem solving
exam,which freequently come
ChatGPT said:
ChatGPT
Here's a list of common C++ string-related problems that often appear in
programming exams, along with their solutions. These problems focus on string
1. Reverse a String
Problem: Write a function to reverse a given string.
Solution:
cpp
Copy code
"Hello, World!"; cout << "Reversed String: " << reverseString(str) <<
endl; return 0; }
Solution:
cpp
Copy code
0; }
3. Count Vowels and Consonants
Problem: Count the number of vowels and consonants in a string.
Solution:
cpp
Copy code
else { consonants++; } } } cout << "Vowels: " << vowels << ",
Consonants: " << consonants << endl; } int main() { string str =
Solution:
cpp
Copy code
Character: " << result << endl; } else { cout << "No Non-Repeating
characters.
Solution:
cpp
Copy code
Solution:
cpp
Copy code
0; }
7. Find All Permutations of a String
Problem: Generate all permutations of a given string.
Solution:
cpp
Copy code
#include <iostream>
#include <string>
#include <algorithm>
{ if (l == r)
} else {
swap(str[l], str[i]);
int main()