0% found this document useful (0 votes)
7 views29 pages

CPP Leetcode

This document is a Leetcode Problem Solving Report submitted by Vishnu Karanth A for the Bachelor of Engineering degree in Artificial Intelligence and Machine Learning at Visvesvaraya Technological University. It includes various coding problems, their implementations, test cases, and explanations for each problem. The report covers a range of problems from easy to hard, showcasing different algorithms and data structures used in the solutions.

Uploaded by

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

CPP Leetcode

This document is a Leetcode Problem Solving Report submitted by Vishnu Karanth A for the Bachelor of Engineering degree in Artificial Intelligence and Machine Learning at Visvesvaraya Technological University. It includes various coding problems, their implementations, test cases, and explanations for each problem. The report covers a range of problems from easy to hard, showcasing different algorithms and data structures used in the solutions.

Uploaded by

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

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

BELAGAVI

Leetcode Problem Solving Report


Submitted in the partial fulfillment for the requirements of the degree of

BACHELOR OF ENGINEERING
IN
ARTIFICIAL INTELLIGENCE AND
MACHINE LEARNING
Submitted By

STUDENTNAME:
VISHNU KARANTH A
USN:1BY24AI191

Under the guidance of

GUIDE NAME
Dr SRIVANI P
DESIGNATION
Department of AIML,
BMSIT&M

DEPARTMENT OF ARTIFICIAL INTELLIGENCE


AND MACHINE LEARNING

BMS INSTITUTE OF TECHNOLOGY & MANAGEMENT


YELAHANKA, BENGALURU - 560064.

2025-2026
Evaluation Sheet

Sl. Proble Problem Mark Mark Marks Tota


No. m Type Name s s (Outpu l
(Cod (Test t)
e) Cases
)
1 Easy Two Sum

2 Easy Roman To
Integer

3 Easy Valid
Parentheses
4 Easy Remove
Duplicates
from Sorted
Array
5 Easy Remove
Element
6 Easy Search
Insert
Position

7 Easy Length of
Last Node
8 Easy Plus One

9 Easy Add Binary

10 Easy Sqrt(x)

11 Medium Add Two


Numbers
12 Medium ZigZag
Conversatio
13 Medium n
Reverse
Integer
14 Medium Devide Two
Integers

2|Page
15 Medium Valid
Sudoku
16 Hard Valid
Number
17 Hard Basic
Calculator

3|Page
Medium

Problem Statement: Two Sum(1)

a. Code Implementation:

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> pairIdx;

for (int i = 0; i < [Link](); ++i) {


int num = nums[i];
if ([Link](target - num) != [Link]()) {
return {i, pairIdx[target - num]};
}
pairIdx[num] = i;
}

return {};
}
};

[Link] Cases Considered:

4|Page
c. Output Screenshots / Console Output:

d. Explanation:

1. We use an unordered_map to store each number and its index.


2. For every element, we calculate the complement (target - current value).
3. If the complement already exists in the map, we return both indices.
4. Otherwise, we store the current number with its index.
5. This approach avoids nested loops.

Problem Statement: Roman To Integer(13)

a. Code Implementation:

class Solution {
public:
int char2num(char a) {
switch (a) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}

int romanToInt(string s) {
int result = 0;
5|Page
for (int i = 0; i < [Link](); i++) {
if (i + 1 < [Link]() && char2num(s[i]) < char2num(s[i + 1])) {
result -= char2num(s[i]);
} else {
result += char2num(s[i]);
}
}
return result;
}
};

b. Test Cases Considered

c. Output Screenshots / Console Output:

d. Explanation:

1. The function char2num() converts each Roman character to its integer value.
2. We traverse the string from left to right.
3. If the current symbol is smaller than the next symbol, it is subtracted from the result.
4. Otherwise, the value is added to the result.
5. This handles cases like IV (4) and IX (9) correctly.
6. Finally, the accumulated result is returned.

6|Page
Problem Statement: Valid Parentheses(20)

a. Code Implementation:

#include <stack>
#include <string>
using namespace std;

class Solution {
public:
bool isValid(string s) {
stack<char> st;

for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
[Link](c);
} else {
if ([Link]()) return false;

char top = [Link]();


[Link]();

if ((c == ')' && top != '(') ||


(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false;
}
}
}
return [Link]();
}
};

b. Test Cases Considered:

7|Page
c. Output Screenshots / Console Output:

d. Explanation:

a. A stack is used to store opening brackets.


b. When an opening bracket is found, it is pushed onto the stack.
c. For a closing bracket, the stack is checked for emptiness.
d. The top element is popped and matched with the closing bracket.
e. If the brackets do not match, the string is invalid.

Problem Statement: Remove Duplicate From Sorted Array(26)

a. Code Implementation:

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int index = 1;
for (int i = 1; i < [Link](); i++) {
if (nums[i] != nums[i - 1]) {
nums[index] = nums[i];
index++;
}
}
return index;
}
};

b. Test Cases Considered:


8|Page
c. Output Screenshots / Console Output:

d. Explanation:

1. The array is already sorted, so duplicates appear next to each other.


2. We maintain an index to track the position of the next unique element.
3. Starting from the second element, each value is compared with the previous one.
4. If the current value is different, it is placed at nums[index].
5. The index is incremented after storing a unique element.

Problem Statement: Remove Element(27)

[Link] Implementation:

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int writeIndex = 0;

for (int i = 0; i < [Link](); i++) {


9|Page
if (nums[i] != val) {
nums[writeIndex] = nums[i];
writeIndex++;
}
}

return writeIndex;
}
};

[Link] Cases Considered:

c. Output Screenshots / Console Output:

d. Explanation:

1. The algorithm uses a writeIndex to track the position for valid elements.
2. We traverse the array and check each element.
3. If the current element is not equal to the given value val, it is copied to
nums[writeIndex].
4. The writeIndex is incremented after placing a valid element.
5. Elements equal to val are skipped.
6. The final value of writeIndex gives the new length of the array.

10 | P a g e
Problem Statement: Search Insert Position(35)

a. Code Implementation:

class Solution {
public:
int searchInsert(vector<int>& nums, int target)
{
int left = 0;
int right = [Link]()-1;
while(left<=right)
{
int mid = left+(right-left)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) left = mid+1;
else right = mid-1;
}
return left;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

11 | P a g e
d. Explanation:

1. Binary search is used since the array is already sorted.


2. Two pointers left and right define the current search range.
3. The middle index is calculated to compare with the target value.
4. If the target is found, its index is returned immediately.
5. If the target is greater, search continues in the right half; otherwise in the left half.
6. When the loop ends, left represents the correct insertion position.

Problem Statement: Length Of Last Node

a. Code Implementation:

class Solution {
public:
int lengthOfLastWord(string s) {
int siz=[Link](),kount=0,flag=0;
for(int i=siz-1;i>=0;i--){
if(s[i]==' '&&flag)break;
if(s[i]!=' '){
flag=1;
kount++;
}
}
return kount;
}
};

b. Test Cases Considered:

12 | P a g e
c. Output Screenshots / Console Output:

d. Explanation:

1. The string is traversed from the end to find the last word.
2. Trailing spaces are ignored until a non-space character is found.
3. Once a character of the last word is detected, a flag is set.
4. Characters are counted until a space is encountered after the word starts.
5. The loop breaks when the word ends.
6. The final count gives the length of the last word.

Problem Statement: Plus One(66)

a. Code Implementation:

class Solution {
public:
vector<int> plusOne(vector<int>& v) {
int n = [Link]();
for(int i = n-1; i >= 0; i--){
if(i == n-1)
v[i]++;
if(v[i] == 10){
v[i] = 0;
if(i != 0){
v[i-1]++;
}

13 | P a g e
else{
v.push_back(0);
v[i] = 1;
}
}
}
return v;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

d. Explanation:

1. The digits are processed from the last position to handle carry easily.
2. One is added to the last digit of the array.
3. If a digit becomes 10, it is set to 0 and a carry is generated.
4. The carry is added to the previous digit.
5. If the most significant digit also becomes 10, a new digit 1 is added at the front.
6. The modified vector represents the final incremented number.

14 | P a g e
Problem Statement: Add Binary(67)

a. Code Implementation:

class Solution
{
public:
string addBinary(string a, string b)
{
string s = "";

int c = 0, i = [Link]() - 1, j = [Link]() - 1;


while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}

return s;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

15 | P a g e
d. Explanation:

1. Two pointers are used to traverse both binary strings from right to left.
2. A variable c is used to store the carry during addition.
3. At each step, digits from both strings and the carry are added.
4. The resulting bit (c % 2) is converted to a character and added to the front of the
result string.
5. The carry is updated by dividing c by 2.
6. The loop continues until all digits and carry are processed.

Problem Statement: Sqrt(x) (69)

a. Code Implementation:

class Solution {
public:
int mySqrt(int x) {
int left=1;
int right=x/2;
int ans=0;
if(x<2){
return x;
}
while(left<=right){
int long mid=left+(right-left)/2;
if(mid*mid==x){
return mid;
}
else if(mid*mid<x){
ans=mid;
16 | P a g e
left=mid+1;
}
else{
right=mid-1;
}

}
return ans;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

d. Explanation:

1. Binary search is used to find the integer square root of x.


2. The search range is set from 1 to x/2 since the square root cannot exceed this.
3. The middle value is squared and compared with x.
4. If mid * mid equals x, mid is returned.
5. If mid * mid is less than x, it becomes a possible answer and search moves right.
6. Otherwise, the search continues in the left half.

Medium

17 | P a g e
Problem Statement: Add Two Numbers(2)

a. Code Implementation:

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy;
ListNode* current = &dummy;
int carry = 0;

while (l1 || l2 || carry) {


int val1 = l1 ? l1->val : 0;
int val2 = l2 ? l2->val : 0;
int total = val1 + val2 + carry;

carry = total / 10;


current->next = new ListNode(total % 10);
current = current->next;

if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
return [Link];
}
};

b. Test Cases Considered:

[Link] Screenshots / Console Output:

18 | P a g e
d. Explanation:

1. A dummy node is used to simplify the creation of the result linked list.
2. The loop continues while there are nodes in either list or a remaining carry.
3. Values from the current nodes of l1 and l2 are added along with the carry.
4. The digit part (total % 10) is stored in a new node, and carry is updated (total / 10).
5. The current pointer moves forward to build the result list.
6. Finally, [Link] is returned as the head of the summed linked list.

Problem Statement: Zig Zag Conversation (6)

a. Code Implementation:

class Solution {
public:
string convert(string s, int n) {
if([Link]()<n || n==1) return s;
int i = 0, k = 0;
bool flag = true; // true = down, false = up
vector<string> v(min(n, int([Link]())));

string res = "";


while (k < [Link]()) {
v[i] += s[k];
if (i == n - 1) flag = false;
if (i == 0) flag = true;
i += flag ? 1 : -1;
k++;

19 | P a g e
}

for (int i = 0; i < n; i++) res += v[i];


return res;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

d. Explanation:

1. If the string length is less than n or n is 1, the original string is returned since zigzag
is not needed.
2. A vector of strings is used to store characters row by row for the zigzag pattern.
3. The index i tracks the current row, while flag controls direction (down or up).

20 | P a g e
4. Characters are appended to the current row, and direction changes at the top and
bottom rows.
5. This process continues until all characters are placed into rows.

Problem Statement: Reverse Integer(7)

a. Code Implementation:

class Solution {
public:
int reverse(int x) {
long long sum = 0;
while (x != 0) {
int rem = x % 10;
sum = sum * 10 + rem;
x = x / 10;
}

if (sum > INT_MAX || sum < INT_MIN) {


return 0;
}

return static_cast<int>(sum);
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

21 | P a g e
d. Explanation:

1. The function reverses an integer by extracting digits one by one using modulo 10.
2. Each extracted digit is appended to sum by multiplying the current value by 10 and
adding the digit.
3. A long long variable is used to safely store the reversed number during computation.
4. The original number is reduced by dividing it by 10 in each iteration.
5. After reversal, the result is checked against 32-bit integer limits.
6. If overflow occurs, the function returns 0; otherwise, the reversed integer is returned.

Problem Statement: Devide Two Integers (29)

a. Code Implementation:

class Solution {
public:
int divide(int dividend, int divisor)
{
if( dividend == INT_MIN && divisor == -1 )
return INT_MAX;
long long int ans = dividend/divisor;
if(ans>INT_MAX)
return INT_MAX;
if(ans<INT_MIN)
return INT_MIN;
return ans;
}
};

b. Test Cases Considered:

22 | P a g e
c. Output Screenshots / Console Output:

d. Explanation:

1. The function performs integer division of dividend by divisor.


2. A special case is handled when dividend is INT_MIN and divisor is -1, which would
cause overflow.
3. Division is done using a long long variable to avoid intermediate overflow.
4. The result is checked to ensure it lies within the 32-bit signed integer range.
5. If the result exceeds INT_MAX or INT_MIN, it is clamped to those limits.
6. The final valid integer quotient is returned.

Problem Statement: Valid Sudoku (36)

23 | P a g e
a. Code Implementation:

class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool rows[9][9] = {false};
bool cols[9][9] = {false};
bool boxes[9][9] = {false};

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


for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '1';
int boxIndex = (i / 3) * 3 + (j / 3);
if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) return false;
rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true;
}
}
}
return true;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

24 | P a g e
d. Explanation:

1. Three 2D boolean arrays track the presence of digits in rows, columns, and 3×3 sub-
boxes.
2. The board is traversed cell by cell using nested loops.
3. For each non-empty cell, the digit is converted to an index from 0 to 8.
4. The corresponding sub-box index is calculated using (i / 3) * 3 + (j / 3).
5. If the digit already exists in the same row, column, or box, the Sudoku is invalid.
6. Otherwise, the digit is marked as seen, and the board is valid if no conflicts are
found.

Hard

Problem Statement: Valid Number (65)

a. Code Implementation:

class Solution {
public:
bool isNumber(string s) {
bool num = false, dot = false, exp = false, numAfterExp = true;

for (int i = 0; i < [Link](); i++) {


char c = s[i];

// Digit
if (isdigit(c)) {
num = true;
if (exp) numAfterExp = true;
}

else if (c == '.') {

25 | P a g e
if (dot || exp) return false;
dot = true;
}
else if (c == 'e' || c == 'E') {
if (exp || !num) return false;
exp = true;
numAfterExp = false;
}

else if (c == '+' || c == '-') {


if (i != 0 && s[i-1] != 'e' && s[i-1] != 'E')
return false;
}
else {
return false;
}
}

return num && numAfterExp;


}
};

b. Test Cases Considered:

26 | P a g e
[Link] Screenshots / Console Output:

d. Explanation:

1. The function validates whether a string represents a valid number using flags for
digits, decimal point, and exponent.
2. Digits set the num flag and ensure at least one digit exists, including after an
exponent.
3. A decimal point is allowed only once and not after an exponent.
4. Exponent (e or E) is valid only if a number appears before it and only once.
5. Signs (+ or -) are allowed only at the start or immediately after an exponent.
6. The string is valid if it contains a number and has digits after the exponent (if
present).

Problem Statement: Basic Calculator (224)

a. Code Implementation:

class Solution {
public:
int calculate(string s) {
long long int sum = 0;
int sign = 1;
stack<pair<int,int>> st;

for(int i=0; i<[Link]();i++){


if(isdigit(s[i])){
27 | P a g e
long long int num = 0;
while(i<[Link]() && isdigit(s[i])){
num = num * 10 + (s[i] - '0');
i++;
}
i--;
sum += num * sign;
sign = 1;
}
else if(s[i] == '('){
[Link]({sum, sign});
sum = 0;
sign = 1;
}
else if(s[i] == ')'){
sum = [Link]().first + ([Link]().second * sum);
[Link]();

}
else if(s[i] == '-'){
sign = -1 * sign;
}
}
return sum;
}
};

b. Test Cases Considered:

c. Output Screenshots / Console Output:

28 | P a g e
d. Explanation:

1. The function evaluates a basic arithmetic expression with +, -, and parentheses.


2. Numbers are parsed digit by digit and added to sum with the current sign.
3. When an opening parenthesis is found, the current sum and sign are pushed onto the
stack.
4. On encountering a closing parenthesis, the stored sign and sum are applied to the
current result.
5. The sign variable handles addition and subtraction operations.
6. After processing the entire string, sum contains the final evaluated result.

LEETCODE PROFILE :

29 | P a g e

You might also like