0% found this document useful (0 votes)
17 views33 pages

Leetcode Part 1

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)
17 views33 pages

Leetcode Part 1

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/ 33

LEET CODE QUESTIONSs

1.Two sum \ / /

121. best time to buy and self stock

217. contains duplica:,e\%

53.maximum subarra

9.Palindrome number
13.Roman to integer

14.longest common prefix

20.valid parentheses

26. remove duplicates from sorted array

27.remove element \/
28.find the index of the first occurrence in a string
1. Two Sum

Easy Y 53895 GP 1793 Q Addtolist [y Share

Given an array of integers nums and an integer target, return indices of the
two numbers such that they add up to target .

You may assume that each input would have exactly one solution, and you
may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9


Output: [0,1]
Explanation: Because nums[@] + nums[1] == 9, we return [©, 1].

1.
Example 2:

Input: nums = [3,2,4], target = 6


Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6


Output: [0,1]

Canctraintc:

1+ class Solution {
2 public:
3 vector<int> twoSum(vector<int>& nums, int target) {
4 int n = nums.size();
5
6~ for (int i = 8; i < nj i++) {
7+ for (int § =i +1; 3 < n; J++) {
8~ if (nums[i] + nums[3] == target) {
9 return {i, j};
10 ¥
11 3}
12 }
13
14 // Return an empty vector if no solution is found
15 return {};
16 }
121. Best Time to Buy and Sell Stock ©
Easy @ dhoa Pk & G

@ Companies

You are given an array prices where prices[i] is the price of a given stock on the it
day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a
different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any
profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]


Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price =
6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed
because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]


Output: 0
Explanation: In this case, no transactions are done and the max
profit = 0.

Constraints:

® 1 <= prices.length <= 10°

e @ <= prices[i] <= 10*


1 class Solution {
2 public:
3 int maxProfit(vector<int>& prices) {
4 int maxp = ©;
5 int minp = prices[@];
6
7 for(int i=0;i<prices.size();i++){
8 minp = min(minp,prices[i]);
9 maxp = max(maxp,prices[i]-minp);
10 3}
11
12 return maxp;
13 }
12 3

217. Contains Duplicate


Easy dy113k P13k & G

& Companies

Given an integer array nums, return true if any value appears at least twice in the array,
and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]


Output: true

Example 2:

Input: nums = [1,2,3,4]


Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]


Output: true
1 class Solution {
2 public:
3 bool containsDuplicate(vector<int>& nums) {
4 for(int i =0;i<nums.size();i++){
5 for(int j=i+1;j<nums.size();j++){
6 if(nums[i] == nums[j]) return true;
7 }
8 }
9 return false;
10
11 }
12}

53. Maximum Subarray


Medium o7 32800 &P 1371 Q AddtoList [} Share

Given an integer array nums , find the subarray with the largest sum, and return
its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]


Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:

Input: nums = [1]


Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]


Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

1
2+ class Solution {
3 public:
G int maxsubarray(vectorcint>t nums) (
c Ent currentsum - nums[8];
i int maxSum - nuns[e];
7
for (int i = 1; § < nums.size(); i++) {
s currentsun' = max(nums[i], currentsun + nuns[3]); / Cho
1 maxsum = nax(maxsun, currentSum); / Update the maxinum
1 3
13 return maxSun;

https://youtube.com/shorts/Az851ZGpV_M?si=_5jeSNfKQ2ufefpW

Watch the above video to understand kadane’s algorithm


9. Palindrome Number

Easy oY 11748 GP 2643 Q Addtolist [0y Share

Given an integer x, return true if x is a palindrome, and false otherwise.

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right
to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to
left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 81 from right to left. Therefore it is not a
palindrome.
1+ class Solution {
2 public:
3v bool isPalindrome(int x) {
ar if (x < @) {
5 return false; // Negative numbers can't be palindromes
6 }
7
8 long long original = x;
9 long long reversed =
18
11 while (x 1= @) {
12 int digit = x % 10;
13 reversed = reversed * 10 + digit;
14 x /= 10;
15 }
16
17 return original == reversed;
18 }
19 ¥

13. Roman to Integer


Easy oY 13093 &P 800 © Addtolist [0y Share

Roman numerals are represented by seven different symbols: I, v, X, L, C,


D and M.

Symbol Value
H
<
X

w
®
0

500
0

1000
2

For example, 2 is written as II in Roman numeral, just two ones added


together. 12 is written as XII, whichissimply X + II.The number 27 is
written as XXVII, whichis XX + V + II.
Roman numerals are usually written largest to smallest from left to right.
However, the numeral for four is not IIII.Instead, the number four is written
as IV.Because the one is before the five we subtract it making four. The same
principle applies to the number nine, which is written as IX . There are six
instances where subtraction is used:

e I canbe placed before v (5)and X (10) to make 4 and 9.


e X can be placed before L (50) and ¢ (100) to make 40 and 90.
e C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V=5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1008, CM = 900, XC = 9@ and IV = 4.
1+ #include <iostream>
2
3+ class Solution {
4 public:
50 int romanToInt(string s) {
6 int result = @
7 int prewalue = €;
8
9+ for (int i = s.length() - 1; i >= &;
10 int current = 6;
11
12 suitch (s[i]) {
13 case 'T':
14 current = 1;
15 break;
16 case 'V':
7 current = 5;
18 break;
19 case 'X':
20 current = 16;
2 break;
22 case 'L':
23 current = 56;
24 break; NEW
25 case 'C':
26 current = 1¢0;

28 case 'D
29 current = 500;
30 break;
31 case 'M':
32 current = 1000;
33 break;
34 )
35
v iF (current < prewalue) {
37 result -= current;
38+ } else {
39 result += current;
40 b}
41 prewalue = current;
2 ¥
43
44 return result;
45
o n NEW
14. Longest Common Prefix
Easy dh 16562 GP 4352 Q Addtolist [fj Share

Write a function to find the longest common prefix string amongst an array of
strings.

If there is no common prefix, return an empty string

Example 1:

Input: strs = ["flower","flow","flight"]


Output: "f1"

Example 2:

Input: strs = ["dog","racecar"”,"car"]


Output: ""
Explanation: There is no common prefix among the input strings.

1+ class Solution {
2 public:
EN string longestCommonPrefix(vector<string>& strs) {
4~ if (strs.empty()) {
H return "
6 ¥
7
8 string prefix = strs[@]; // Initialize the prefix with the first string
9
10+ For (int i = 1; i < strs.size(); i++) {
11 int j = o
12+ while (j < prefix.length() & j < strs[i].length() && prefix[j] == strs[i][j])
{
13 J++s
14 }
15
16 prefix = prefix.substr(®, j); // Update the prefix with the common prefix
17
18
19 return prefix;
20 }
21 }s
22
NEW

Your previous code was restored from your local storage. Reset
to default
20. Valid Parentheses

Easy dh 22909 GP 1596 Q) AddtoList [fj Share

Given a string s containing just the characters "(*, ')*, '{", '}", '['
and ']', determine if the input string is valid.

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.


2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Example 2:

Input: s = "()[1{}"
Output: true

Example 3:

Input: s = "(]"
Output: false
-+ class Solution {
public:
v bool isValid(string s) {
stack<char> stack;
for (char ch : s) {
if (ch == (" || ch == "{' || cn [IDIN
stack.push(ch); // Push open brackets onto the stack
- } else {
. if (stack.empty()) {
return false; // No matching open bracket for a close bracket
}
char top = stack.top();
stack.pop();
/] Check if the current close bracket matches the last open bracket
if ((ch == ') 8& top = '(') ||
(ch
v (ch
return false;

}
NEW
return stack.empty(); // If the stack is empty, 21l brackets are matched

26. Remove Duplicates from Sorted Array


Easy b 13361 GP 17650 Q AddtolList [) Share

Given an integer array nums sorted in non-decreasing order, remove the


duplicates in-place such that each unique element appears only once. The
relative order of the elements should be kept the same. Then return the
number of unique elements in nums .

Consider the number of unique elements of nums to be k, to get accepted,


you need to do the following things:

e Change the array nums such that the first k elements of nums contain
the unique elements in the order they were present in nums initially. The
remaining elements of nums are not important as well as the size of
nums .

e Return k.
Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array


int[] expectedNums = [...]; // The expected answer with correct
length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = @; 1 < k; i++) {
assert nums[i] == expectedNums[i];

If all assertions pass, then your solution will be accepted.

Example1:

Input: nums = [1,1,2]


Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first
two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence
they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]


Output: 5, nums = [0,1,2,3,4,
, , ,_,_]

Explanation: Your function should return k = 5, with the first


five elements of nums being @, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence
they are underscores).
1+ class solution {
2 public:
3 int removeDuplicates(vector<int>& nums) {
a~ if (nums.empty()) {
5 return ©; // If the input array is empty, there are no unique elements.
6 }
7
8 int k = 1; // Initialize k to 1, as the first element is always unique.
9
10~ for (int i = 1; i < nums.size(); i++) {
11 // If the current element is different from the previous one, update nums[k]
12+ if (nums[i] != nums[i - 1]) {
13 nums[k] = nums[i];
14 k++; // Increment k to represent the count of unique elements.
15 }
16 }
17
18 return k;
19 }
20 b
2

27. Remove Element


Easy oY 1712 GP 2558 Q Addtolist [0 Share

Given an integer array nums and an integer val, remove all occurrences of
val in nums in-place. The order of the elements may be changed. Then return
the number of elements in nums which are not equal to val .

Consider the number of elements in nums which are not equal to val be k,
to get accepted, you need to do the following things:

e Change the array nums such that the first k elements of nums contain
the elements which are not equal to val . The remaining elements of
nums are not important as well as the size of nums .
® Return k.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array


int val = ...; // Value to remove
Lusiom Juage:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array


int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct
length.
// It is sorted with no values
equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, @, k); // Sort the first k elements of nums
for (int i = @; i < actuallength; i++) {
assert nums[i] == expectedNums[i];

If all assertions pass, then your solution will be accepted.


Example 1:

Input: nums = [3';2,2,3], val = 3


Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first
two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence
they are underscores).

Example 2:

Input: nums = [©,1,2,2,3,0,4,2], val = 2


Output: 5, nums = [0,1,4,0,3,
, ,_]
Explanation: Your function should return k = 5, with the first
five elements of nums containing ©, ©, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence
they are underscores).

1+ class Solution {
2 public:
3y int removeElement(vector<int>& nums, int val) {
4 int index = 9;
5v for(int i = @; i< nums.size(); i++){
6~ if(nums[i] != val){
7 nums[index] = nums[i];
8 index++;
9 ¥
10 3}
11 return index;
12 }
13 }
28. Find the Index of the First Occurrence in a String
Easy Y 5220 GP 318 Q Addtolist [0y Share

Given two strings needle and haystack, return the index of the first
occurrence of needle in haystack,or -1 if needle is not part of haystack .

Example 1:

Input: haystack = "sadbutsad", needle = "sad"


Output: @
Explanation: "sad" occurs at index © and 6.
The first occurrence is at index @, so we return @.

Example 2:

Input: haystack = "leetcode", needle = "leeto"


Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return

1+ class Solution {
2 public:
3v int strstr(string haystack, string needle) {
a int m = haystack.length();
5 int n = needle.length();
6
7 if (n==e) {
8 return @; // Empty needle is always found at the beginning.
9 b
10
1 if (m<n) {
12 return -1; // If haystack is shorter than needle, there is no match.
13 b
14
15+ For (int i = @; i <= m - n; i++) {
16 int j;
17~ for (3 =0;
3 <n; j++) {
18+ i (haystack[i + 3] != needle[§]) {
19 break; // If a character doesn't match, break the inner loop.
20 ¥
21 }
22
23+ if (§ ==n) {
24 return i; // If the inner loop completed without breaking, we found NEW
match.
¥
return -1; // No match found in the haystack.

b NEW
// 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