0% found this document useful (0 votes)
16 views13 pages

112

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views13 pages

112

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

// 1.

Two Sum

#include <iostream> // For input/output operations

#include <vector> // For using vectors

using namespace std; // Standard namespace

// Class to implement the Two Sum solution

class Solution1 {

public:

vector<int> twoSum(vector<int>& nums, int target) { // Function to find two indices

int n = nums.size(); // Get the size of the array

for (int i = 0; i < n; i++) { // Outer loop to iterate through each element

for (int j = i + 1; j < n; j++) { // Inner loop to find a pair

if (nums[i] + nums[j] == target) { // Check if the pair adds up to the target

return {i, j}; // Return the indices if found

return {}; // Return an empty vector if no solution is found

};

int main() {

Solution1 solution; // Create an instance of Solution1

vector<int> nums = {2, 7, 11, 15}; // Input array

int target = 9; // Target sum

vector<int> result = solution.twoSum(nums, target); // Call the twoSum function

cout << "Indices: [" << result[0] << ", " << result[1] << "]" << endl; // Output result

return 0; // End of program


}

// 2. Best Time to Buy and Sell Stock

#include <iostream> // For input/output

#include <vector> // For using vectors

#include <algorithm> // For min and max functions

using namespace std; // Standard namespace

// Class to implement the Stock Profit solution

class Solution2 {

public:

int maxProfit(vector<int>& prices) { // Function to calculate maximum profit

int maxProfit = 0; // Initialize maxProfit to 0

int minPrice = prices[0]; // Initialize minPrice to the first element

for (int i = 1; i < prices.size(); i++) { // Loop through the prices array

minPrice = min(minPrice, prices[i]); // Update minPrice if a lower price is found

maxProfit = max(maxProfit, prices[i] - minPrice); // Update maxProfit if a better


profit is found

return maxProfit; // Return the maximum profit

};

int main() {

Solution2 solution; // Create an instance of Solution2

vector<int> prices = {7, 1, 5, 3, 6, 4}; // Input prices array

cout << "Max Profit: " << solution.maxProfit(prices) << endl; // Output the result

return 0; // End of program


}

// 3. Contains Duplicate

#include <iostream> // For input/output operations

#include <vector> // For using vectors

#include <algorithm> // For sorting the array

using namespace std; // Standard namespace

// Class to implement the Contains Duplicate solution

class Solution3 {

public:

bool containsDuplicate(vector<int>& nums) { // Function to check for duplicates

sort(nums.begin(), nums.end()); // Sort the array

for (int i = 1; i < nums.size(); i++) { // Loop through the sorted array

if (nums[i] == nums[i - 1]) return true; // Check for consecutive duplicates

return false; // Return false if no duplicates are found

};

int main() {

Solution3 solution; // Create an instance of Solution3

vector<int> nums = {1, 2, 3, 1}; // Input array

cout << (solution.containsDuplicate(nums) ? "True" : "False") << endl; // Output result

return 0; // End of program

// 4. Maximum Subarray
#include <iostream> // For input/output operations

#include <vector> // For using vectors

#include <algorithm> // For max function

using namespace std; // Standard namespace

// Class to implement the Maximum Subarray solution

class Solution4 {

public:

int maxSubArray(vector<int>& nums) { // Function to find the maximum subarray sum

int currentSum = nums[0]; // Initialize current sum to the first element

int maxSum = nums[0]; // Initialize max sum to the first element

for (int i = 1; i < nums.size(); i++) { // Loop through the array starting from the second
element

currentSum = max(nums[i], currentSum + nums[i]); // Update current sum

maxSum = max(maxSum, currentSum); // Update max sum

return maxSum; // Return the maximum sum

};

int main() {

Solution4 solution; // Create an instance of Solution4

vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; // Input array

cout << "Max Subarray Sum: " << solution.maxSubArray(nums) << endl; // Output
result

return 0; // End of program

// 5. Palindrome Number
#include <iostream> // For input/output operations

using namespace std; // Standard namespace

// Class to implement the Palindrome Number solution

class Solution5 {

public:

bool isPalindrome(int x) { // Function to check if a number is a palindrome

if (x < 0) return false; // Negative numbers are not palindromes

long original = x; // Store the original number

long reversed = 0; // Initialize reversed number to 0

while (x != 0) { // Loop until the number becomes 0

int digit = x % 10; // Extract the last digit

reversed = reversed * 10 + digit; // Append the digit to reversed number

x /= 10; // Remove the last digit from the number

return original == reversed; // Check if the original and reversed numbers are the
same

};

int main() {

Solution5 solution; // Create an instance of Solution5

int x = 121; // Input number

cout << (solution.isPalindrome(x) ? "True" : "False") << endl; // Output result

return 0; // End of program

// 6. Roman to Integer
#include <iostream> // For input/output operations

#include <string> // For using strings

using namespace std; // Standard namespace

// Class to implement the Roman to Integer solution

class Solution6 {

public:

int romanToInt(string s) { // Function to convert Roman numeral to integer

int result = 0; // Initialize result to 0

int prevValue = 0; // Initialize the previous value to 0

for (int i = s.length() - 1; i >= 0; i--) { // Loop through the string from the end

int currentValue = 0; // Initialize current value to 0

switch (s[i]) { // Determine the value of the current Roman character

case 'I': currentValue = 1; break;

case 'V': currentValue = 5; break;

case 'X': currentValue = 10; break;

case 'L': currentValue = 50; break;

case 'C': currentValue = 100; break;

case 'D': currentValue = 500; break;

case 'M': currentValue = 1000; break;

if (currentValue < prevValue) { // If the current value is less than the previous value

result -= currentValue; // Subtract the current value from the result

} else {

result += currentValue; // Otherwise, add the current value to the result

prevValue = currentValue; // Update the previous value

}
return result; // Return the final result

};

int main() {

Solution6 solution; // Create an instance of Solution6

string s = "MCMXCIV"; // Input Roman numeral

cout << "Integer: " << solution.romanToInt(s) << endl; // Output result

return 0; // End of program

// 7. Longest Common Prefix

#include <iostream> // For input/output operations

#include <vector> // For using vectors

#include <string> // For using strings

using namespace std; // Standard namespace

// Class to implement the Longest Common Prefix solution

class Solution7 {

public:

string longestCommonPrefix(vector<string>& strs) { // Function to find the longest


common prefix

if (strs.empty()) return ""; // Return empty string if the input is empty

string prefix = strs[0]; // Initialize prefix with the first string

for (int i = 1; i < strs.size(); i++) { // Loop through the strings

int j = 0; // Initialize index to compare characters

while (j < prefix.length() && j < strs[i].length() && prefix[j] == strs[i][j]) {


j++; // Increment index if characters match

prefix = prefix.substr(0, j); // Update the prefix to the common prefix

if (prefix.empty()) break; // Exit if no common prefix exists

return prefix; // Return the longest common prefix

};

int main() {

Solution7 solution; // Create an instance of Solution7

vector<string> strs = {"flower", "flow", "flight"}; // Input strings

cout << "Longest Common Prefix: " << solution.longestCommonPrefix(strs) << endl; //
Output result

return 0; // End of program

// 8. Valid Parentheses

#include <iostream> // For input/output operations

#include <stack> // For using stack data structure

#include <string> // For using strings

using namespace std; // Standard namespace

// Class to implement the Valid Parentheses solution

class Solution8 {

public:

bool isValid(string s) { // Function to check if parentheses are valid


stack<char> stack; // Stack to store open parentheses

for (char ch : s) { // Loop through each character in the string

if (ch == '(' || ch == '{' || ch == '[') {

stack.push(ch); // Push open parentheses onto the stack

} else {

if (stack.empty()) return false; // If stack is empty, parentheses are invalid

char top = stack.top(); // Get the top element of the stack

stack.pop(); // Remove the top element

// Check if the current close parenthesis matches the top open parenthesis

if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) {

return false; // Return false if parentheses don't match

return stack.empty(); // If stack is empty, all parentheses are matched

};

int main() {

Solution8 solution; // Create an instance of Solution8

string s = "()[]{}"; // Input string

cout << (solution.isValid(s) ? "True" : "False") << endl; // Output result

return 0; // End of program

// 9. Remove Duplicates from Sorted Array

#include <iostream> // For input/output operations

#include <vector> // For using vectors


using namespace std; // Standard namespace

// Class to implement the Remove Duplicates from Sorted Array solution

class Solution9 {

public:

int removeDuplicates(vector<int>& nums) { // Function to remove duplicates

if (nums.empty()) return 0; // Return 0 if the input array is empty

int k = 1; // Initialize k to 1, as the first element is always unique

for (int i = 1; i < nums.size(); i++) { // Loop through the array starting from the second
element

if (nums[i] != nums[i - 1]) { // If the current element is different from the previous
one

nums[k++] = nums[i]; // Update the element at index k and increment k

return k; // Return the count of unique elements

};

int main() {

Solution9 solution; // Create an instance of Solution9

vector<int> nums = {1, 1, 2}; // Input array

int k = solution.removeDuplicates(nums); // Call the function

cout << "Length: " << k << ", Array: ["; // Output result

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

cout << nums[i] << (i < k - 1 ? ", " : ""); // Print unique elements

cout << "]" << endl; // Close the array output

return 0; // End of program


}

// 10. Remove Element

#include <iostream> // For input/output operations

#include <vector> // For using vectors

using namespace std; // Standard namespace

// Class to implement the Remove Element solution

class Solution10 {

public:

int removeElement(vector<int>& nums, int val) { // Function to remove all occurrences


of a value

int index = 0; // Initialize index to 0

for (int i = 0; i < nums.size(); i++) { // Loop through the array

if (nums[i] != val) { // If the current element is not equal to the value to be removed

nums[index++] = nums[i]; // Update the element at index and increment index

return index; // Return the count of remaining elements

};

int main() {

Solution10 solution; // Create an instance of Solution10

vector<int> nums = {3, 2, 2, 3}; // Input array

int val = 3; // Value to be removed

int k = solution.removeElement(nums, val); // Call the function

cout << "Length: " << k << ", Array: ["; // Output result
for (int i = 0; i < k; i++) {

cout << nums[i] << (i < k - 1 ? ", " : ""); // Print remaining elements

cout << "]" << endl; // Close the array output

return 0; // End of program

// 11. Find the Index of the First Occurrence in a String

#include <iostream> // For input/output operations

#include <string> // For using strings

using namespace std; // Standard namespace

// Class to implement the Find the Index of the First Occurrence in a String solution

class Solution11 {

public:

int strStr(string haystack, string needle) { // Function to find the index of the first
occurrence

int m = haystack.length(); // Get the length of the haystack

int n = needle.length(); // Get the length of the needle

if (n == 0) return 0; // If the needle is empty, return 0

if (m < n) return -1; // If the haystack is shorter than the needle, return -1

for (int i = 0; i <= m - n; i++) { // Loop through the haystack

int j; // Initialize index for the needle

for (j = 0; j < n; j++) { // Loop through the needle

if (haystack[i + j] != needle[j]) break; // Break if characters don't match

if (j == n) return i; // If all characters match, return the starting index

}
return -1; // Return -1 if no match is found

};

int main() {

Solution11 solution; // Create an instance of Solution11

string haystack = "sadbutsad"; // Input haystack string

string needle = "sad"; // Input needle string

cout << "Index: " << solution.strStr(haystack, needle) << endl; // Output result

return 0; // End of program

You might also like