Ultimate Coding Cheat Sheet
Ultimate Coding Cheat Sheet
@the_dev_xplained
THE ULTIMATE CODING CHEAT SHEET
Follow us on Instagram
@the_DevXplained @the_dev_xplained
○
Example:
5 = 0101
3 = 0011
5 ^ 3 = 0110 (6)
○ a = a ^ b
○ Stores XOR result in a.
○ Example: 5 ^ 3 = 6, so now a = 6 and b = 3.
2. Second XOR Operation:
○ b = a ^ b
○ Restores b to original a.
○ Example: 6 ^ 3 = 5, so now b = 5 and a = 6.
3. Third XOR Operation:
○ a = a ^ b
○ Restores a to original b.
@the_DevXplained @the_dev_xplained
○
Final Result
● Original: a = 5, b = 3
● After Swap: a = 3, b = 5
Code Implementation
Python
def xor_swap(a, b):
a=a^b
b=a^b
a=a^b
return a, b
# Example usage
a, b = 5, 3
print("Before Swap: a =", a, ", b =", b)
a, b = xor_swap(a, b)
print("After Swap: a =", a, ", b =", b)
C++
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 3;
cout << "Before Swap: a = " << a << ", b = " << b << endl;
xorSwap(a, b);
cout << "After Swap: a = " << a << ", b = " << b << endl;
return 0;
@the_DevXplained @the_dev_xplained
○
Java
public class XorSwap {
public static void xorSwap(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
[Link]("After Swap: a = " + a + ", b = " + b);
}
● x ^ x = 0
● x ^ 0 = x
● x ^ y ^ x = y (since x ^ x = 0, it cancels out)
Algorithm: To determine whether a number is even or odd without using the modulo (%)
operator, we can utilize bitwise operations or arithmetic properties:
○ The least significant bit (LSB) of an even number is always 0 (e.g., 4 -> 100, 6
-> 110).
○ The LSB of an odd number is always 1 (e.g., 3 -> 011, 5 -> 101).
○ Performing num & 1 checks if the LSB is 1 (odd) or 0 (even).
2. Using Division and Multiplication:
@the_DevXplained @the_dev_xplained
○
Code Implementation
Python:
# Example Usage
num = int(input("Enter a number: "))
print("Even" if is_even(num) else "Odd")
C++:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << (isEven(num) ? "Even" : "Odd") << endl;
return 0;
}
@the_DevXplained @the_dev_xplained
○
Java:
import [Link];
Algorithm Explanation
A number is a power of 2 if it has exactly one bit set in its binary representation. This means that
for a number n, it should satisfy the condition:
n & (n - 1) == 0
1. If n is less than or equal to 0, return False (since negative numbers and zero are not
powers of 2).
2. Perform the bitwise AND operation n & (n - 1). If the result is 0, then n is a power of
2; otherwise, it is not.
@the_DevXplained @the_dev_xplained
○
Python
def is_power_of_two(n):
if n <= 0:
return False
return (n & (n - 1)) == 0
# Example usage:
n = 16
print(is_power_of_two(n)) # Output: True
C++
#include <iostream>
using namespace std;
bool isPowerOfTwo(int n) {
if (n <= 0) return false;
return (n & (n - 1)) == 0;
}
int main() {
int n = 16;
cout << (isPowerOfTwo(n) ? "True" : "False") << endl; // Output: True
return 0;
}
Java
public class PowerOfTwoCheck {
public static boolean isPowerOfTwo(int n) {
if (n <= 0) return false;
return (n & (n - 1)) == 0;
}
@the_DevXplained @the_dev_xplained
○
Algorithm Explanation
The Euclidean algorithm is an efficient method for computing the Greatest Common Divisor
(GCD) of two numbers. The GCD of two integers is the largest number that divides both of them
without leaving a remainder.
Python:
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Example usage:
print(gcd(48, 18)) # Output: 6
C++:
#include <iostream>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
cout << gcd(48, 18) << endl; // Output: 6
return 0;
}
Java:
public class GCD {
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
Algorithm:
A prime number is a number greater than 1 that has no divisors other than 1 and itself. To check
if a number n is prime:
1. If n is less than or equal to 1, return False (since prime numbers start from 2).
2. If n is 2 or 3, return True (since they are the smallest prime numbers).
3. If n is even or divisible by 3, return False.
4. Check divisibility from 5 to sqrt(n) with increments of 6 (i and i+2) since all primes
greater than 3 are of the form 6k ± 1.
5. If no divisors are found, return True.
@the_DevXplained @the_dev_xplained
○
Python
import math
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i=5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Example usage:
print(is_prime(29)) # Output: True
C++
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
@the_DevXplained @the_dev_xplained
○
int main() {
cout << (isPrime(29) ? "True" : "False") << endl; // Output: True
return 0;
}
Java
public class PrimeCheck {
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
String Problems:
1. Reverse a string
Algorithm Explanation
Reversing a string means rearranging its characters in the opposite order. The following
approaches can be used:
1. Iterative Approach: Use a loop to swap characters from both ends moving toward the
center.
2. Using Built-in Functions: Many languages provide built-in functions to reverse a string
efficiently.
@the_DevXplained @the_dev_xplained
○
3. Using Recursion: Recursively reverse the substring excluding the first character and
append the first character at the end.
Python:
def reverse_string(s):
return s[::-1] # Using slicing
# Example usage:
print(reverse_string("hello")) # Output: "olleh"
C++:
#include <iostream>
#include <algorithm>
using namespace std;
string reverseString(string s) {
reverse([Link](), [Link]());
return s;
}
int main() {
cout << reverseString("hello") << endl; // Output: "olleh"
return 0;
}
Java:
public class ReverseString {
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
Algorithm:
@the_DevXplained @the_dev_xplained
○
A palindrome is a string that reads the same forward and backward. To check if a string is a
palindrome efficiently, we use the Two-Pointer Approach, which avoids extra space usage for
reversing the string.
Two-Pointer Approach:
1. Use two pointers: one at the beginning (left) and one at the end (right) of the string.
2. Compare the characters at both positions.
3. If they match, move left forward and right backward.
4. If any mismatch is found, return False (not a palindrome).
5. Continue until the pointers meet or cross each other.
This approach runs in O(N) time complexity and uses O(1) extra space.
Python:
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
# Example usage:
print(is_palindrome("racecar")) # Output: True
C++:
#include <iostream>
using namespace std;
bool isPalindrome(string s) {
int left = 0, right = [Link]() - 1;
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
@the_DevXplained @the_dev_xplained
○
int main() {
cout << (isPalindrome("racecar") ? "True" : "False") << endl; // Output: True
return 0;
}
Java:
public class PalindromeCheck {
public static boolean isPalindrome(String s) {
int left = 0, right = [Link]() - 1;
while (left < right) {
if ([Link](left) != [Link](right)) {
return false;
}
left++;
right--;
}
return true;
}
Algorithm:
Iterative Approach:
This approach runs in O(N) time complexity and uses O(1) extra space.
Python:
@the_DevXplained @the_dev_xplained
○
# Example usage:
print(count_char("hello", 'l')) # Output: 2
C++:
#include <iostream>
using namespace std;
int main() {
cout << countChar("hello", 'l') << endl; // Output: 2
return 0;
}
Java:
public class CharacterCount {
public static int countChar(String s, char c) {
int count = 0;
for (char ch : [Link]()) {
if (ch == c) count++;
}
return count;
}
@the_DevXplained @the_dev_xplained
○
}
}
Algorithm Explanation
An anagram is a word or phrase formed by rearranging the letters of another. The most efficient
way to check if two strings are anagrams is the Frequency Count Approach.
1. If the lengths of both strings are different, they cannot be anagrams.
2. Use an array (or hashmap) to count the occurrences of each character in the first string.
3. Decrease the count for each character in the second string.
4. If all counts return to zero, the strings are anagrams.
Time Complexity: O(N) (since we traverse both strings once) Space Complexity: O(1) (since the
character count array has a fixed size of 26 for lowercase letters or 256 for extended ASCII)
Python:
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
# Example usage:
print(is_anagram("listen", "silent")) # Output: True
C++:
#include <iostream>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
cout << (isAnagram("listen", "silent") ? "True" : "False") << endl; // Output: True
return 0;
}
Java:
public class AnagramCheck {
public static boolean isAnagram(String s1, String s2) {
if ([Link]() != [Link]()) return false;
@the_DevXplained @the_dev_xplained
○
}
5. Find the first repeated character in a string:
Algorithm
To find the first repeated character in a string efficiently, we use the Hash Set Approach.
Time Complexity: O(N) (since we traverse the string once) Space Complexity: O(N) (in the worst
case, we store all unique characters)
Python:
def first_repeated_char(s):
seen = set()
for char in s:
if char in seen:
return char
[Link](char)
return None # No repeated character found
# Example usage:
print(first_repeated_char("abca")) # Output: 'a'
C++:
#include <iostream>
#include <unordered_set>
using namespace std;
@the_DevXplained @the_dev_xplained
○
}
return '\0'; // No repeated character found
}
int main() {
cout << firstRepeatedChar("abca") << endl; // Output: 'a'
return 0;
}
Java:
import [Link];
Algorithm
To check if two strings are rotations of each other efficiently, we use the Concatenation
Approach.
Concatenation Approach:
1. If the lengths of the two strings are not equal, they cannot be rotations.
2. Concatenate the first string with itself.
3. Check if the second string is a substring of this concatenated string.
@the_DevXplained @the_dev_xplained
○
Time Complexity: O(N) (substring search is efficient) Space Complexity: O(N) (concatenated
string takes extra space)
Python
def are_rotations(s1, s2):
if len(s1) != len(s2):
return False
return s2 in (s1 + s1)
# Example usage:
print(are_rotations("abcd", "cdab")) # Output: True
C++
#include <iostream>
using namespace std;
int main() {
cout << (areRotations("abcd", "cdab") ? "True" : "False") << endl; // Output: True
return 0;
}
Java
public class StringRotationCheck {
public static boolean areRotations(String s1, String s2) {
if ([Link]() != [Link]()) return false;
return (s1 + s1).contains(s2);
}
@the_DevXplained @the_dev_xplained
○
Algorithm
To find the longest common prefix among an array of strings efficiently, we use the Vertical
Scanning Approach.
Time Complexity: O(N * M) (where N is the number of strings and M is the length of the shortest
string) Space Complexity: O(1) (no extra space used)
Python:
def longest_common_prefix(strs):
if not strs:
return ""
for i in range(len(strs[0])):
char = strs[0][i]
for s in strs[1:]:
if i >= len(s) or s[i] != char:
return strs[0][:i]
return strs[0]
# Example usage:
print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"
C++:
#include <iostream>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
char c = strs[0][i];
for (int j = 1; j < [Link](); j++) {
if (i >= strs[j].length() || strs[j][i] != c)
return strs[0].substr(0, i);
}
}
return strs[0];
}
int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << longestCommonPrefix(strs) << endl; // Output: "fl"
return 0;
}
Java:
public class LongestCommonPrefix {
public static String longestCommonPrefix(String[] strs) {
if ([Link] == 0) return "";
@the_DevXplained @the_dev_xplained
○
Algorithm
To efficiently count vowels and consonants in a given string, we use the Single Pass
Approach:
Time Complexity: O(N) (where N is the length of the string) Space Complexity: O(1) (constant
extra space used)
Python:
def count_vowels_consonants(s):
vowels = set("aeiouAEIOU")
vowel_count = consonant_count = 0
for char in s:
if [Link]():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
# Example usage:
print(count_vowels_consonants("Hello World!")) # Output: (3, 7)
C++:
#include <iostream>
#include <cctype>
using namespace std;
@the_DevXplained @the_dev_xplained
○
for (char ch : s) {
if (isalpha(ch)) {
if ([Link](ch) != string::npos)
vowel_count++;
else
consonant_count++;
}
}
return {vowel_count, consonant_count};
}
int main() {
auto result = countVowelsConsonants("Hello World!");
cout << "Vowels: " << [Link] << ", Consonants: " << [Link] << endl; // Output:
Vowels: 3, Consonants: 7
return 0;
}
Java:
public class CountVowelsConsonants {
public static int[] countVowelsConsonants(String s) {
String vowels = "aeiouAEIOU";
int vowelCount = 0, consonantCount = 0;
@the_DevXplained @the_dev_xplained
○
Algorithm
To efficiently remove all adjacent duplicate characters from a string, we use the Stack-Based
Approach:
Stack-Based Approach:
Time Complexity: O(N) (where N is the length of the string) Space Complexity: O(N) (in the
worst case, storing all distinct characters in the stack)
Python:
def remove_adjacent_duplicates(s):
stack = []
for char in s:
if stack and stack[-1] == char:
[Link]()
else:
[Link](char)
return "".join(stack)
# Example usage:
print(remove_adjacent_duplicates("abbaca")) # Output: "ca"
C++:
@the_DevXplained @the_dev_xplained
○
#include <iostream>
#include <stack>
using namespace std;
string removeAdjacentDuplicates(string s) {
string result = "";
for (char ch : s) {
if (![Link]() && [Link]() == ch)
result.pop_back();
else
result.push_back(ch);
}
return result;
}
int main() {
cout << removeAdjacentDuplicates("abbaca") << endl; // Output: "ca"
return 0;
}
Java:
public class RemoveAdjacentDuplicates {
public static String removeAdjacentDuplicates(String s) {
StringBuilder stack = new StringBuilder();
for (char ch : [Link]()) {
if ([Link]() > 0 && [Link]([Link]() - 1) == ch) {
[Link]([Link]() - 1);
} else {
[Link](ch);
}
}
return [Link]();
}
@the_DevXplained @the_dev_xplained
○
Algorithm
To implement the atoi() function, which converts a string to an integer, we use an Iterative
Parsing Approach that handles spaces, signs, and overflow conditions.
Optimized Approach:
Time Complexity: O(N) (where N is the length of the string) Space Complexity: O(1) (constant
extra space used)
Python
def my_atoi(s):
s = [Link]()
if not s:
return 0
sign = 1
if s[0] in ('-', '+'):
sign = -1 if s[0] == '-' else 1
s = s[1:]
res, i = 0, 0
while i < len(s) and s[i].isdigit():
res = res * 10 + int(s[i])
i += 1
res *= sign
return max(min(res, 2**31 - 1), -2**31)
# Example usage:
print(my_atoi(" -42")) # Output: -42
C++
#include <iostream>
@the_DevXplained @the_dev_xplained
○
#include <climits>
using namespace std;
int myAtoi(string s) {
int i = 0, sign = 1, result = 0;
while (i < [Link]() && s[i] == ' ') i++; // Trim spaces
int main() {
cout << myAtoi(" -42") << endl; // Output: -42
return 0;
}
Java:
public class StringToIntegerAtoi {
public static int myAtoi(String s) {
s = [Link]();
if ([Link]()) return 0;
@the_DevXplained @the_dev_xplained
○
Algorithm
To find the longest word in a given string efficiently, we use the Iterative Split Approach:
Optimized Approach:
1. Split the String: Use built-in functions to split the string into words.
2. Iterate Over Words: Compare lengths to determine the longest word.
3. Handle Edge Cases: Consider empty strings and multiple longest words.
Time Complexity: O(N) (where N is the length of the string, as we traverse it once) Space
Complexity: O(1) (only a few extra variables used)
Python
def longest_word(s):
words = [Link]()
return max(words, key=len, default="")
# Example usage:
print(longest_word("The quick brown fox jumps over the lazy dog")) # Output: "quick"
C++
#include <iostream>
#include <sstream>
using namespace std;
@the_DevXplained @the_dev_xplained
○
string longestWord(string s) {
istringstream iss(s);
string word, longest;
while (iss >> word) {
if ([Link]() > [Link]()) {
longest = word;
}
}
return longest;
}
int main() {
cout << longestWord("The quick brown fox jumps over the lazy dog") << endl; // Output:
"quick"
return 0;
}
Java
public class LongestWordFinder {
public static String longestWord(String s) {
String[] words = [Link]("\\s+");
String longest = "";
for (String word : words) {
if ([Link]() > [Link]()) {
longest = word;
}
}
return longest;
}
Algorithm
@the_DevXplained @the_dev_xplained
○
To find all substrings of a given string efficiently, we use a nested loop approach:
Optimized Approach:
1. Iterate Over Start Index: Use a loop to pick the starting index of the substring.
2. Iterate Over End Index: Use another loop to pick the ending index and extract
substrings.
3. Store or Process Substrings: Print or collect substrings as needed.
Time Complexity: O(N²) (since we generate substrings using two nested loops) Space
Complexity: O(1) (if printing substrings directly; O(N²) if storing them in a list)
Python
def all_substrings(s):
n = len(s)
for i in range(n):
for j in range(i + 1, n + 1):
print(s[i:j]) # Print each substring
# Example usage:
all_substrings("abc")
Output:
a
ab
abc
b
bc
c
C++
#include <iostream>
using namespace std;
void allSubstrings(string s) {
int n = [Link]();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
cout << [Link](i, j - i) << endl;
@the_DevXplained @the_dev_xplained
○
}
}
}
int main() {
allSubstrings("abc");
return 0;
}
Java
public class SubstringFinder {
public static void allSubstrings(String s) {
int n = [Link]();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
[Link]([Link](i, j));
}
}
}
This approach ensures that all possible substrings are efficiently extracted while keeping the
implementation simple.
Array Problems:
Algorithm
To find the unique number in an array where all other numbers appear twice, we use the XOR
(^) operator. The XOR operation has the following properties:
@the_DevXplained @the_dev_xplained
○
By XORing all numbers together, the duplicate numbers cancel out (result in 0), and only the
unique number remains.
Time Complexity: O(N) (traverses the array once) Space Complexity: O(1) (constant space
usage)
Python
def find_unique(arr):
unique = 0
for num in arr:
unique ^= num # XOR operation
return unique
# Example usage:
print(find_unique([2, 3, 5, 3, 2])) # Output: 5
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 3, 5, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
cout << findUnique(arr, n) << endl; // Output: 5
return 0;
}
Java
public class UniqueNumber {
public static int findUnique(int[] arr) {
int unique = 0;
@the_DevXplained @the_dev_xplained
○
This approach ensures optimal performance using bitwise XOR, making it both efficient and
memory-friendly.
Algorithm
To find pairs in an array that sum to a given target, we use the HashMap (Dictionary)
Approach for optimal efficiency.
1. Traverse the array and maintain a hashmap (dictionary) to store numbers encountered.
2. For each number num, compute the complement target - num.
3. If the complement exists in the hashmap, a pair is found.
4. Otherwise, store num in the hashmap and continue.
Time Complexity: O(N) (single pass through the array) Space Complexity: O(N) (to store
elements in the hashmap)
Python
def find_pairs(arr, target):
seen = {}
pairs = []
for num in arr:
complement = target - num
if complement in seen:
[Link]((complement, num))
seen[num] = True
@the_DevXplained @the_dev_xplained
○
return pairs
# Example usage:
print(find_pairs([2, 7, 4, 8, 1, 5], 9)) # Output: [(2, 7), (4, 5)]
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {2, 7, 4, 8, 1, 5};
int target = 9;
vector<pair<int, int>> result = findPairs(arr, target);
for (auto& p : result) {
cout << "(" << [Link] << ", " << [Link] << ")\n";
}
return 0;
}
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
This solution ensures we find all pairs efficiently using a hashmap-based lookup.
Algorithm
To find the maximum sum of a contiguous subarray, we use Kadane's Algorithm, which
efficiently finds the largest sum in O(N) time complexity.
@the_DevXplained @the_dev_xplained
○
Time Complexity: O(N) (single pass through the array) Space Complexity: O(1) (constant
space used)
Python
def max_subarray_sum(arr):
max_sum = float('-inf')
current_sum = 0
return max_sum
# Example usage:
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # Output: 6
C++
#include <iostream>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
vector<int> arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << maxSubarraySum(arr) << endl; // Output: 6
return 0;
}
Java
public class KadaneAlgorithm {
public static int maxSubarraySum(int[] arr) {
int maxSum = Integer.MIN_VALUE, currentSum = 0;
This implementation ensures we find the maximum contiguous subarray sum in O(N) time
complexity efficiently.
@the_DevXplained @the_dev_xplained
○
Algorithm
To rotate an array by k positions efficiently, we use the Reverse Approach, which achieves the
result in O(N) time complexity and O(1) space complexity.
Reverse Approach
Time Complexity: O(N) (since we perform three passes of reversal) Space Complexity: O(1)
(no extra space used)
Python
def rotate_array(arr, k):
n = len(arr)
k %= n # Handle cases where k > n
[Link]()
arr[:k] = reversed(arr[:k])
arr[k:] = reversed(arr[k:])
return arr
# Example usage:
print(rotate_array([1, 2, 3, 4, 5, 6, 7], 3)) # Output: [5, 6, 7, 1, 2, 3, 4]
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
@the_DevXplained @the_dev_xplained
○
reverse([Link](), [Link]());
reverse([Link](), [Link]() + k);
reverse([Link]() + k, [Link]());
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5, 6, 7};
rotateArray(arr, 3);
for (int num : arr) cout << num << " "; // Output: 5 6 7 1 2 3 4
return 0;
}
Java
import [Link].*;
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
@the_DevXplained @the_dev_xplained
○
This approach ensures efficient in-place rotation using O(N) time complexity.
Algorithm
To remove duplicates from a sorted array efficiently, we use the Two-Pointer Approach. This
method ensures an O(N) time complexity with O(1) extra space.
Two-Pointer Approach
Time Complexity: O(N) (traversing the array once) Space Complexity: O(1) (modifying the
array in-place)
Python
def remove_duplicates(arr):
if not arr:
return 0
@the_DevXplained @the_dev_xplained
○
# Example usage:
arr = [1, 1, 2, 2, 3, 4, 4, 5]
new_length = remove_duplicates(arr)
print(arr[:new_length]) # Output: [1, 2, 3, 4, 5]
C++
#include <iostream>
#include <vector>
using namespace std;
int j = 0;
for (int i = 1; i < [Link](); i++) {
if (arr[i] != arr[j]) {
j++;
arr[j] = arr[i];
}
}
return j + 1;
}
int main() {
vector<int> arr = {1, 1, 2, 2, 3, 4, 4, 5};
int newLength = removeDuplicates(arr);
for (int i = 0; i < newLength; i++) cout << arr[i] << " "; // Output: 1 2 3 4 5
return 0;
}
Java
public class RemoveDuplicates {
public static int removeDuplicates(int[] arr) {
if ([Link] == 0) return 0;
int j = 0;
@the_DevXplained @the_dev_xplained
○
This approach modifies the array in-place and ensures O(N) time complexity.
Python
def find_missing(arr):
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] > mid + 1:
right = mid
@the_DevXplained @the_dev_xplained
○
else:
left = mid + 1
return left + 1
# Example usage:
arr = [1, 2, 3, 4, 6, 7, 8]
print(find_missing(arr)) # Output: 5
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 6, 7, 8};
int n = sizeof(arr) / sizeof(arr[0]);
cout << findMissing(arr, n) << endl; // Output: 5
return 0;
}
Java
public class MissingNumber {
public static int findMissing(int[] arr) {
int left = 0, right = [Link] - 1;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] > mid + 1)
right = mid;
@the_DevXplained @the_dev_xplained
○
else
left = mid + 1;
}
return left + 1;
}
1. Initialize two variables to track the largest and second largest elements.
2. Iterate through the array to update these variables accordingly.
3. Return the second largest element.
Python
def second_largest(arr):
first, second = float('-inf'), float('-inf')
for num in arr:
if num > first:
second, first = first, num
elif num > second and num != first:
second = num
return second if second != float('-inf') else -1
# Example usage:
arr = [10, 20, 4, 45, 99]
print(second_largest(arr)) # Output: 45
C++
#include <iostream>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
int arr[] = {10, 20, 4, 45, 99};
int n = sizeof(arr) / sizeof(arr[0]);
cout << secondLargest(arr, n) << endl; // Output: 45
return 0;
}
Java
public class SecondLargest {
public static int secondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
return (second == Integer.MIN_VALUE) ? -1 : second;
}
@the_DevXplained @the_dev_xplained
○
8. Reverse an Array
1. Use two pointers: one at the beginning and one at the end.
2. Swap the elements at these positions.
3. Move the pointers towards the center until they meet.
Python
def reverse_array(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
# Example usage:
arr = [1, 2, 3, 4, 5]
print(reverse_array(arr)) # Output: [5, 4, 3, 2, 1]
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, n);
@the_DevXplained @the_dev_xplained
○
for (int i = 0; i < n; i++) cout << arr[i] << " ";
return 0;
}
Java
public class ReverseArray {
public static void reverseArray(int[] arr) {
int left = 0, right = [Link] - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
reverseArray(arr);
for (int num : arr) [Link](num + " ");
}
}
Python
def move_zeros(arr):
pos = 0 # Position to place non-zero elements
for num in arr:
if num != 0:
arr[pos] = num
pos += 1
@the_DevXplained @the_dev_xplained
○
# Example usage:
arr = [0, 1, 0, 3, 12]
print(move_zeros(arr)) # Output: [1, 3, 12, 0, 0]
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = sizeof(arr) / sizeof(arr[0]);
moveZeros(arr, n);
for (int i = 0; i < n; i++) cout << arr[i] << " ";
return 0;
}
Java
public class MoveZeros {
public static void moveZeros(int[] arr) {
int pos = 0;
for (int num : arr) {
if (num != 0) arr[pos++] = num;
}
while (pos < [Link]) arr[pos++] = 0;
}
public static void main(String[] args) {
@the_DevXplained @the_dev_xplained
○
Algorithm:
Python
def intersection(arr1, arr2):
i, j = 0, 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] == arr2[j]:
[Link](arr1[i])
i += 1
j += 1
elif arr1[i] < arr2[j]:
i += 1
else:
j += 1
return result
# Example usage:
print(intersection([1, 2, 4, 5, 6], [2, 3, 5, 7])) # Output: [2, 5]
C++
#include <iostream>
@the_DevXplained @the_dev_xplained
○
#include <vector>
using namespace std;
int main() {
vector<int> arr1 = {1, 2, 4, 5, 6};
vector<int> arr2 = {2, 3, 5, 7};
vector<int> result = intersection(arr1, arr2);
for (int num : result) cout << num << " ";
return 0;
}
Java
import [Link].*;
class Intersection {
public static List<Integer> intersection(int[] arr1, int[] arr2) {
List<Integer> result = new ArrayList<>();
int i = 0, j = 0;
while (i < [Link] && j < [Link]) {
if (arr1[i] == arr2[j]) {
[Link](arr1[i]);
i++;
j++;
@the_DevXplained @the_dev_xplained
○
Algorithm
Time Complexity: O(N + M) (where N and M are sizes of the two arrays) Space Complexity:
O(N + M) (for storing unique elements)
Python
def union_of_arrays(arr1, arr2):
return list(set(arr1) | set(arr2))
# Example usage:
arr1 = [1, 2, 3, 4, 5]
arr2 = [3, 4, 5, 6, 7]
print(union_of_arrays(arr1, arr2)) # Output: [1, 2, 3, 4, 5, 6, 7]
C++
@the_DevXplained @the_dev_xplained
○
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
int main() {
vector<int> arr1 = {1, 2, 3, 4, 5};
vector<int> arr2 = {3, 4, 5, 6, 7};
vector<int> result = unionOfArrays(arr1, arr2);
for (int num : result) cout << num << " "; // Output: 1 2 3 4 5 6 7
return 0;
}
Java
import [Link].*;
Algorithm
@the_DevXplained @the_dev_xplained
○
Time Complexity: O(N) (since we traverse the array once and insert/look up elements in a
HashSet in O(1) time on average) Space Complexity: O(N) (for storing elements in the
HashSet)
Python
def first_repeating_element(arr):
seen = set()
for num in arr:
if num in seen:
return num
[Link](num)
return -1
# Example usage:
arr = [10, 5, 3, 4, 3, 5, 6]
print(first_repeating_element(arr)) # Output: 5
C++
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
int arr[] = {10, 5, 3, 4, 3, 5, 6};
@the_DevXplained @the_dev_xplained
○
Java
import [Link].*;
13. Find the Element That Appears More Than n/2 Times (Majority Element)
1. Initialize two variables: candidate to store a potential majority element and count to
track its frequency.
2. Traverse the array:
○ If count is 0, set candidate to the current element.
○ If the current element is the same as candidate, increase count.
○ Otherwise, decrease count.
3. The remaining candidate will be the majority element.
4. Verify by counting occurrences (optional if the problem guarantees existence).
@the_DevXplained @the_dev_xplained
○
Python
def majority_element(nums):
candidate, count = None, 0
for num in nums:
if count == 0:
candidate = num
count += 1 if num == candidate else -1
return candidate
# Example usage:
arr = [3, 3, 4, 2, 3, 3, 3]
print(majority_element(arr)) # Output: 3
C++
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {3, 3, 4, 2, 3, 3, 3};
cout << majorityElement(arr) << endl; // Output: 3
return 0;
}
Java
public class MajorityElement {
public static int majorityElement(int[] nums) {
int candidate = 0, count = 0;
for (int num : nums) {
@the_DevXplained @the_dev_xplained
○
Algorithm
1. Use a HashSet (or unordered_set in C++) to store all unique elements of the array.
2. Iterate through each element and check if it is the start of a sequence (i.e., num - 1 is
not present in the set).
3. If it is the start of a sequence, count the length of the consecutive numbers.
4. Update the maximum sequence length encountered.
Python
def longest_consecutive(nums):
num_set = set(nums)
longest_streak = 0
@the_DevXplained @the_dev_xplained
○
return longest_streak
# Example usage:
nums = [100, 4, 200, 1, 3, 2]
print(longest_consecutive(nums)) # Output: 4
C++
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
return longestStreak;
}
int main() {
vector<int> nums = {100, 4, 200, 1, 3, 2};
cout << longestConsecutive(nums) << endl; // Output: 4
return 0;
}
@the_DevXplained @the_dev_xplained
○
Java
import [Link];
int longestStreak = 0;
return longestStreak;
}
15. Sort an array of 0s, 1s, and 2s (Dutch National Flag Problem)
Algorithm
@the_DevXplained @the_dev_xplained
○
# Example usage:
arr = [2, 0, 1, 2, 1, 0]
sort_colors(arr)
print(arr) # Output: [0, 0, 1, 1, 2, 2]
C++
#include <iostream>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
vector<int> arr = {2, 0, 1, 2, 1, 0};
sortColors(arr);
for (int num : arr) cout << num << " "; // Output: 0 0 1 1 2 2
return 0;
}
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
16. Find the product of all elements except the current element (without
division)
Algorithm:
Python
def product_except_self(nums):
n = len(nums)
result = [1] * n
left = 1
for i in range(n):
result[i] = left
left *= nums[i]
right = 1
for i in range(n-1, -1, -1):
result[i] *= right
right *= nums[i]
return result
C++
#include <iostream>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
result[i] *= left;
left *= nums[i];
}
for (int i = n - 1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
}
Java
import [Link].*;
Algorithm
1. Use the Sliding Window Technique with two pointers (start and end).
2. Maintain a current_sum to store the sum of elements between start and end.
@the_DevXplained @the_dev_xplained
○
Python
def subarray_sum(arr, target):
start, current_sum = 0, 0
for end in range(len(arr)):
current_sum += arr[end]
while current_sum > target:
current_sum -= arr[start]
start += 1
if current_sum == target:
return arr[start:end+1]
return []
# Example usage:
arr = [1, 4, 20, 3, 10, 5]
target = 33
print(subarray_sum(arr, target)) # Output: [20, 3, 10]
C++
#include <iostream>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
vector<int> arr = {1, 4, 20, 3, 10, 5};
int target = 33;
vector<int> result = subarraySum(arr, target);
for (int num : result) cout << num << " ";
return 0;
}
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
Algorithm
Python
def find_smallest_missing_positive(arr):
n = len(arr)
for i in range(n):
while 1 <= arr[i] <= n and arr[arr[i] - 1] != arr[i]:
arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1] # Swap
for i in range(n):
if arr[i] != i + 1:
return i + 1
return n + 1
# Example usage:
arr = [3, 4, -1, 1]
print(find_smallest_missing_positive(arr)) # Output: 2
C++
#include <iostream>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
vector<int> arr = {3, 4, -1, 1};
cout << findSmallestMissingPositive(arr) << endl; // Output: 2
return 0;
}
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
Dictionary Problems:
Algorithm:
Python
from collections import defaultdict
def group_anagrams(words):
anagrams = defaultdict(list)
for word in words:
anagrams[tuple(sorted(word))].append(word)
return list([Link]())
C++
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
vector<string> words = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> result = groupAnagrams(words);
for (auto group : result) {
for (string word : group) cout << word << " ";
cout << endl;
}
return 0;
}
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
Algorithm:
Python
from collections import Counter
def first_non_repeating(s):
freq = Counter(s)
for char in s:
if freq[char] == 1:
return char
return None
print(first_non_repeating("swiss"))
C++
#include <iostream>
#include <unordered_map>
using namespace std;
char firstNonRepeating(string s) {
unordered_map<char, int> freq;
for (char ch : s) freq[ch]++;
for (char ch : s) if (freq[ch] == 1) return ch;
return '_';
}
int main() {
cout << firstNonRepeating("swiss") << endl;
return 0;
}
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
Algorithm:
Python
from collections import Counter
def count_frequency(arr):
freq = Counter(arr)
return dict(freq)
print(count_frequency([1, 2, 2, 3, 3, 3, 4]))
# Output: {1: 1, 2: 2, 3: 3, 4: 1}
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
@the_DevXplained @the_dev_xplained
○
int main() {
vector<int> arr = {1, 2, 2, 3, 3, 3, 4};
countFrequency(arr);
return 0;
}
// Output: 1 : 1\n2 : 2\n3 : 3\n4 : 1
Java
import [Link].*;
Algorithm:
@the_DevXplained @the_dev_xplained
○
Python
from collections import Counter
import heapq
print(top_k_frequent([1,1,1,2,2,3,3,3,3,4], 2))
# Output: [3, 1]
C++
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
int main() {
vector<int> nums = {1,1,1,2,2,3,3,3,3,4};
int k = 2;
vector<int> result = topKFrequent(nums, k);
for (int num : result) cout << num << " ";
return 0;
}
// Output: 3 1
@the_DevXplained @the_dev_xplained
○
Java
import [Link].*;
Algorithm:
Python
from collections import Counter
import re
def most_frequent_word(paragraph):
words = [Link](r'\w+', [Link]())
freq = Counter(words)
return max(freq, key=[Link])
@the_DevXplained @the_dev_xplained
○
print(most_frequent_word("The quick brown fox jumps over the lazy dog. The fox was quick."))
# Output: "the"
C++
#include <iostream>
#include <sstream>
#include <unordered_map>
using namespace std;
int main() {
string paragraph = "The quick brown fox jumps over the lazy dog. The fox was quick.";
cout << mostFrequentWord(paragraph) << endl;
return 0;
}
// Output: "the"
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
Algorithm:
Python
@the_DevXplained @the_dev_xplained
○
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> findCommonElements(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) {
int i = 0, j = 0, k = 0;
vector<int> result;
while (i < [Link]() && j < [Link]() && k < [Link]()) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
result.push_back(arr1[i]);
i++; j++; k++;
} else if (arr1[i] < arr2[j]) {
i++;
} else if (arr2[j] < arr3[k]) {
j++;
} else {
k++;
}
}
return result;
}
Java
import [Link].*;
public class CommonElements {
public static List<Integer> findCommonElements(int[] arr1, int[] arr2, int[] arr3) {
int i = 0, j = 0, k = 0;
List<Integer> result = new ArrayList<>();
while (i < [Link] && j < [Link] && k < [Link]) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
[Link](arr1[i]);
i++; j++; k++;
} else if (arr1[i] < arr2[j]) {
i++;
} else if (arr2[j] < arr3[k]) {
j++;
} else {
@the_DevXplained @the_dev_xplained
○
k++;
}
}
return result;
}
}
Algorithm:
1. Use a sliding window approach with two pointers (left and right).
2. Use a hash set to track characters in the window.
3. Expand right pointer if the character is unique; shrink left if it's a duplicate.
4. Update max length accordingly.
Python
def longest_substring(s):
char_set = set()
left = max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
C++
#include <iostream>
#include <unordered_set>
using namespace std;
int longestSubstring(string s) {
unordered_set<char> charSet;
int left = 0, maxLength = 0;
for (int right = 0; right < [Link](); right++) {
while ([Link](s[right]) != [Link]()) {
[Link](s[left]);
@the_DevXplained @the_dev_xplained
○
left++;
}
[Link](s[right]);
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
Java
import [Link].*;
public class LongestSubstring {
public static int longestSubstring(String s) {
Set<Character> charSet = new HashSet<>();
int left = 0, maxLength = 0;
for (int right = 0; right < [Link](); right++) {
while ([Link]([Link](right))) {
[Link]([Link](left));
left++;
}
[Link]([Link](right));
maxLength = [Link](maxLength, right - left + 1);
}
return maxLength;
}
}
Algorithm:
Python
@the_DevXplained @the_dev_xplained
○
C++
#include <iostream>
#include <unordered_map>
using namespace std;
bool areArraysEqual(vector<int>& arr1, vector<int>& arr2) {
if ([Link]() != [Link]()) return false;
unordered_map<int, int> freq;
for (int num : arr1) freq[num]++;
for (int num : arr2) {
if (freq[num] == 0) return false;
freq[num]--;
}
return true;
}
Java
import [Link].*;
public class ArrayEquality {
public static boolean areArraysEqual(int[] arr1, int[] arr2) {
if ([Link] != [Link]) return false;
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr1) [Link](num, [Link](num, 0) + 1);
for (int num : arr2) {
if ( || [Link](num) == 0) return false;
[Link](num, [Link](num) - 1);
}
return true;
}
}
9. Find all elements in an array that appear more than ⌊n/3⌋ times
Algorithm:
@the_DevXplained @the_dev_xplained
○
1. Use Boyer-Moore Voting Algorithm to identify at most two potential candidates.
2. Count occurrences of these candidates in the array.
3. Return elements that appear more than ⌊n/3⌋ times. Time Complexity: O(N) Space
Complexity: O(1)
Python
from collections import Counter
def find_majority_elements(arr):
if not arr:
return []
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
@the_DevXplained @the_dev_xplained
○
count1 = count2 = 0;
for (int num : nums) {
if (num == candidate1) count1++;
else if (num == candidate2) count2++;
}
vector<int> result;
if (count1 > [Link]() / 3) result.push_back(candidate1);
if (count2 > [Link]() / 3) result.push_back(candidate2);
return result;
}
int main() {
vector<int> nums = {3,3,2,2,2,1,1,1,1};
vector<int> res = findMajorityElements(nums);
for (int num : res) cout << num << " ";
return 0;
}
// Output: 1 2
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
Algorithm:
Python
from collections import defaultdict
def group_anagrams(words):
anagrams = defaultdict(list)
for word in words:
anagrams[tuple(sorted(word))].append(word)
return list([Link]())
C++
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
@the_DevXplained @the_dev_xplained
○
Java
import [Link].*;
Algorithm:
1. Use a sliding window approach with a hash set to track the last k elements.
2. If a duplicate is found within k distance, return True.
3. Otherwise, return False. Time Complexity: O(N) Space Complexity: O(k)
@the_DevXplained @the_dev_xplained
○
Python
def contains_nearby_duplicate(nums, k):
seen = set()
for i, num in enumerate(nums):
if num in seen:
return True
[Link](num)
if len(seen) > k:
[Link](nums[i - k])
return False
C++
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
Java
import [Link].*;
@the_DevXplained @the_dev_xplained
○
}
}
@the_DevXplained @the_dev_xplained