Leetcode Part 1
Leetcode Part 1
1.Two sum \ / /
53.maximum subarra
9.Palindrome number
13.Roman to integer
20.valid parentheses
27.remove element \/
28.find the index of the first occurrence in a string
1. Two Sum
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.
Example 1:
1.
Example 2:
Example 3:
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:
Example 2:
Constraints:
& 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:
Example 2:
Example 3:
Given an integer array nums , find the subarray with the largest sum, and return
its sum.
Example 1:
Example 3:
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
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 ¥
Symbol Value
H
<
X
w
®
0
500
0
1000
2
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.
Example 1:
Example 2:
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
Given a string s containing just the characters "(*, ')*, '{", '}", '['
and ']', determine if the input string is valid.
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
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:
assert k == expectedNums.length;
for (int i = @; 1 < k; i++) {
assert nums[i] == expectedNums[i];
Example1:
Example 2:
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:
The judge will test your solution with the following code:
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];
Example 2:
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:
Example 2:
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
class Solution1 {
public:
for (int i = 0; i < n; i++) { // Outer loop to iterate through each element
};
int main() {
cout << "Indices: [" << result[0] << ", " << result[1] << "]" << endl; // Output result
class Solution2 {
public:
for (int i = 1; i < prices.size(); i++) { // Loop through the prices array
};
int main() {
cout << "Max Profit: " << solution.maxProfit(prices) << endl; // Output the result
// 3. Contains Duplicate
class Solution3 {
public:
for (int i = 1; i < nums.size(); i++) { // Loop through the sorted array
};
int main() {
// 4. Maximum Subarray
#include <iostream> // For input/output operations
class Solution4 {
public:
for (int i = 1; i < nums.size(); i++) { // Loop through the array starting from the second
element
};
int main() {
cout << "Max Subarray Sum: " << solution.maxSubArray(nums) << endl; // Output
result
// 5. Palindrome Number
#include <iostream> // For input/output operations
class Solution5 {
public:
return original == reversed; // Check if the original and reversed numbers are the
same
};
int main() {
// 6. Roman to Integer
#include <iostream> // For input/output operations
class Solution6 {
public:
for (int i = s.length() - 1; i >= 0; i--) { // Loop through the string from the end
if (currentValue < prevValue) { // If the current value is less than the previous value
} else {
}
return result; // Return the final result
};
int main() {
cout << "Integer: " << solution.romanToInt(s) << endl; // Output result
class Solution7 {
public:
};
int main() {
cout << "Longest Common Prefix: " << solution.longestCommonPrefix(strs) << endl; //
Output result
// 8. Valid Parentheses
class Solution8 {
public:
} else {
// Check if the current close parenthesis matches the top open parenthesis
if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) {
};
int main() {
class Solution9 {
public:
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
};
int main() {
cout << "Length: " << k << ", Array: ["; // Output result
cout << nums[i] << (i < k - 1 ? ", " : ""); // Print unique elements
class Solution10 {
public:
if (nums[i] != val) { // If the current element is not equal to the value to be removed
};
int main() {
cout << "Length: " << k << ", Array: ["; // Output result
for (int i = 0; i < k; i++) {
cout << nums[i] << (i < k - 1 ? ", " : ""); // Print remaining elements
// 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
if (m < n) return -1; // If the haystack is shorter than the needle, return -1
}
return -1; // Return -1 if no match is found
};
int main() {
cout << "Index: " << solution.strStr(haystack, needle) << endl; // Output result