Merge branch 'master' into master

This commit is contained in:
Muhammad Junaid Khalid
2024-10-11 12:24:53 +05:00
committed by GitHub
3 changed files with 236 additions and 74 deletions

View File

@@ -302,6 +302,7 @@
* [Kadanes3](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/kadanes3.cpp)
* [Kelvin To Celsius](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/kelvin_to_celsius.cpp)
* [Lfu Cache](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/lfu_cache.cpp)
* [Longest Substring Without Repeating Characters](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/longest_substring_without_repeating_characters.cpp)
* [Lru Cache](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/lru_cache.cpp)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/matrix_exponentiation.cpp)
* [Palindrome Of Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/others/palindrome_of_number.cpp)

View File

@@ -0,0 +1,110 @@
/**
* @file
* @brief Solution for Longest Substring Without Repeating Characters problem.
* @details
* Problem link: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
*
* Intuition:
* 1) The intuition is straightforward and simple. We track the frequency of characters.
* 2) Since we can't use a string to track the longest substring without repeating characters efficiently (as removing a character from the front of a string isn't O(1)), we optimize the solution using a deque approach.
*
* Approach:
* 1) Initialize an unordered_map to track the frequency of characters.
* 2) Use a deque for pushing characters, and update the result deque (`res`) with the current deque (`temp`)
* whenever we find a longer substring.
* 3) Use a while loop to reduce the frequency from the front, incrementing `i`,
* and removing characters from the `temp` deque as we no longer need them.
* 4) Return `res.size()` as we are interested in the length of the longest substring.
*
* Time Complexity: O(N)
* Space Complexity: O(N)
*
* I hope this helps to understand.
* Thank you!
* @author [Ashish Kumar Sahoo](github.com/ashish5kmax)
**/
#include <iostream> // for IO Operations
#include <unordered_map> // for std::unordered_map
#include <deque> // for std::deque
#include <string> // for string class/string datatype which is taken as input
#include <cassert> // for assert
/**
* @class Longest_Substring
* @brief Class that solves the Longest Substring Without Repeating Characters problem.
*/
class Longest_Substring {
public:
/**
* @brief Function to find the length of the longest substring without repeating characters.
* @param s Input string.
* @return Length of the longest substring.
*/
int lengthOfLongestSubstring(std::string s) {
// If the size of string is 1, then it will be the answer.
if (s.size() == 1) return 1;
// Map used to store the character frequency.
std::unordered_map<char, int> m;
int n = s.length();
// Deque to remove from back if repeating characters are present.
std::deque<char> temp;
std::deque<char> res;
int i, j;
// Sliding window approach using two pointers.
for (i = 0, j = 0; i < n && j < n;) {
m[s[j]]++;
// If repeating character found, update result and remove from the front.
if (m[s[j]] > 1) {
if (temp.size() > res.size()) {
res = temp;
}
while (m[s[j]] > 1) {
temp.pop_front();
m[s[i]]--;
i++;
}
}
// Add the current character to the deque.
temp.push_back(s[j]);
j++;
}
// Final check to update result.
if (temp.size() > res.size()) {
res = temp;
}
return res.size(); // Return the length of the longest substring.
}
};
/**
* @brief Self-test implementations
* @returns void
*/
static void tests() {
Longest_Substring soln;
assert(soln.lengthOfLongestSubstring("abcabcbb") == 3);
assert(soln.lengthOfLongestSubstring("bbbbb") == 1);
assert(soln.lengthOfLongestSubstring("pwwkew") == 3);
assert(soln.lengthOfLongestSubstring("") == 0); // Test case for empty string
assert(soln.lengthOfLongestSubstring("abcdef") == 6); // Test case for all unique characters
assert(soln.lengthOfLongestSubstring("a") == 1); // Single character
std::cout << "All test cases passed!" << std::endl;
}
/**
* @brief Main function.
* @return 0 on successful execution.
*/
int main() {
tests(); // run self-test implementations
return 0;
}

View File

@@ -2,82 +2,133 @@
* @file
* @brief Bubble sort algorithm
*
* The working principle of the Bubble sort algorithm:
* @details
* Bubble sort algorithm is the bubble sorting algorithm. The most important reason
* for calling the bubble is that the largest number is thrown at the end of this
* algorithm. This is all about the logic. In each iteration, the largest number is
* expired and when iterations are completed, the sorting takes place.
*
* What is Swap?
*
* Swap in the software means that two variables are displaced.
* An additional variable is required for this operation. x = 5, y = 10.
* We want x = 10, y = 5. Here we create the most variable to do it.
*
* ```cpp
* int z;
* z = x;
* x = y;
* y = z;
* ```
*
* The above process is a typical displacement process.
* When x assigns the value to x, the old value of x is lost.
* That's why we created a variable z to create the first value of the value of x,
* and finally, we have assigned to y.
*
* ## Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case)
*
* ### Best Case
* Bubble Sort Best Case Performance. \f$O(n)\f$. However, you
* can't get the best status in the code we shared above. This happens on the
* optimized bubble sort algorithm. It's right down there.
*
* ### Worst Case
* Bubble Sort Worst Case Performance is \f$O(n^{2})\f$. Why is that? Because if you
* remember Big O Notation, we were calculating the complexity of the algorithms in
* the nested loops. The \f$n * (n - 1)\f$ product gives us \f$O(n^{2})\f$ performance. In the
* worst case all the steps of the cycle will occur.
*
* ### Average Case
* Bubble Sort is not an optimal algorithm. In average, \f$O(n^{2})\f$ performance is taken.
*
* @author [Deepak](https://github.com/Deepak-j-p)
* @author [Nguyen Phuc Chuong](https://github.com/hollowcrust)
*/
Bubble sort algorithm is the bubble sorting algorithm. The most important reason
for calling the bubble is that the largest number is thrown at the end of this
algorithm. This is all about the logic. In each iteration, the largest number is
expired and when iterations are completed, the sorting takes place.
#include <algorithm> /// for std::is_sorted
#include <cassert> /// for assert
#include <iostream> /// for IO implementations
#include <string> /// for std::string
#include <utility> /// for std::pair, std::swap
#include <vector> /// for std::vector, std::vector::push_back, std::vector::size
What is Swap?
Swap in the software means that two variables are displaced.
An additional variable is required for this operation. x = 5, y = 10.
We want x = 10, y = 5. Here we create the most variable to do it.
int z;
z = x;
x = y;
y = z;
The above process is a typical displacement process.
When x assigns the value to x, the old value of x is lost.
That's why we created a variable z to create the first value of the value of x,
and finally, we have assigned to y.
Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case)
Bubble Sort Worst Case Performance is O (n²). Why is that? Because if you
remember Big O Notation, we were calculating the complexity of the algorithms in
the nested loops. The n * (n - 1) product gives us O (n²) performance. In the
worst case all the steps of the cycle will occur. Bubble Sort (Avarage Case)
Performance. Bubble Sort is not an optimal algorithm. in average, O (n²)
performance is taken. Bubble Sort Best Case Performance. O (n). However, you
can't get the best status in the code we shared above. This happens on the
optimized bubble sort algorithm. It's right down there.
*/
#include <iostream>
#include <vector>
int main() {
int n;
bool swap_check = true;
std::cout << "Enter the amount of numbers to sort: ";
std::cin >> n;
std::vector<int> numbers;
std::cout << "Enter " << n << " numbers: ";
int num;
// Input
for (int i = 0; i < n; i++) {
std::cin >> num;
numbers.push_back(num);
/**
* @namespace sorting
* @brief Sorting algorithms
*/
namespace sorting {
/**
* @namespace bubble_sort
* @brief Bubble sort algorithm
*/
namespace bubble_sort {
/**
* @brief Bubble sort algorithm
* @param array An array to be sorted
* @return The array sorted in ascending order
*/
template <typename T>
std::vector<T> bubble_sort(std::vector<T>& array) {
// swap_check flag to terminate the function early
// if there is no swap occurs in one iteration.
bool swap_check = true;
int size = array.size();
for (int i = 0; (i < size) && (swap_check); i++) {
swap_check = false;
for (int j = 0; j < size - 1 - i; j++) {
if (array[j] > array[j + 1]) {
swap_check = true;
std::swap(array[j], array[j + 1]);
}
}
}
// Bubble Sorting
for (int i = 0; (i < n) && (swap_check); i++) {
swap_check = false;
for (int j = 0; j < n - 1 - i; j++) {
if (numbers[j] > numbers[j + 1]) {
swap_check = true;
std::swap(numbers[j],
numbers[j + 1]); // by changing swap location.
// I mean, j. If the number is
// greater than j + 1, then it
// means the location.
}
}
}
// Output
std::cout << "\nSorted Array : ";
for (int i = 0; i < numbers.size(); i++) {
if (i != numbers.size() - 1) {
std::cout << numbers[i] << ", ";
} else {
std::cout << numbers[i] << std::endl;
}
}
return 0;
return array;
}
} // namespace bubble_sort
} // namespace sorting
/**
* @brief Self-test implementation
* @return void
*/
static void test() {
std::vector<int> vec_1 = {3, 1, -9, 0};
std::vector<int> sorted_1 = sorting::bubble_sort::bubble_sort(vec_1);
std::vector<int> vec_2 = {3};
std::vector<int> sorted_2 = sorting::bubble_sort::bubble_sort(vec_2);
std::vector<int> vec_3 = {10, 10, 10, 10, 10};
std::vector<int> sorted_3 = sorting::bubble_sort::bubble_sort(vec_3);
std::vector<float> vec_4 = {1234, -273.1, 23, 150, 1234, 1555.55, -2000};
std::vector<float> sorted_4 = sorting::bubble_sort::bubble_sort(vec_4);
std::vector<char> vec_5 = {'z', 'Z', 'a', 'B', ' ', 'c', 'a'};
std::vector<char> sorted_5 = sorting::bubble_sort::bubble_sort(vec_5);
std::vector<std::string> vec_6 = {"Hello", "hello", "Helo", "Hi", "hehe"};
std::vector<std::string> sorted_6 = sorting::bubble_sort::bubble_sort(vec_6);
std::vector<std::pair<int, char>> vec_7 = {{10, 'c'}, {2, 'z'}, {10, 'a'}, {0, 'b'}, {-1, 'z'}};
std::vector<std::pair<int, char>> sorted_7 = sorting::bubble_sort::bubble_sort(vec_7);
assert(std::is_sorted(sorted_1.begin(), sorted_1.end()));
assert(std::is_sorted(sorted_2.begin(), sorted_2.end()));
assert(std::is_sorted(sorted_3.begin(), sorted_3.end()));
assert(std::is_sorted(sorted_4.begin(), sorted_4.end()));
assert(std::is_sorted(sorted_5.begin(), sorted_5.end()));
assert(std::is_sorted(sorted_6.begin(), sorted_6.end()));
assert(std::is_sorted(sorted_7.begin(), sorted_7.end()));
}
/**
* @brief Main function
* @return 0 on exit
*/
int main() {
test();
return 0;
}