Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment1.1
Student Name: Kunal Shaw UID: 21BCS2144
Branch: CSE Section/Group: 608-A
Semester: 6th Date of Performance: Jan 15, 2024
Subject Name: Advanced Programing Subject Code: 21CSP-351
Lab - II
1. Aim: To implement the concepts of Arrays, Stacks, Queues linked list
2. Objective:
a. 3 sum
b. Jump Game II
Problem 1:
3. Script and Output:
a. Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such
that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.Notice that the
solution set must not contain duplicate triplets.
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
if (nums.size() < 3)
return {};

vector<vector<int>> ans;

ranges::sort(nums);

for (int i = 0; i + 2 < nums.size(); ++i) {


if (i > 0 && nums[i] == nums[i - 1])
continue;

int l = i + 1;
int r = nums.size() - 1;
while (l < r) {
const int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
ans.push_back({nums[i], nums[l++], nums[r--]});
while (l < r && nums[l] == nums[l - 1])
++l;
while (l < r && nums[r] == nums[r + 1])
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
--r;
} else if (sum < 0) {
++l;
} else {
--r;
}
}
}

return ans;
}
};

Problem 2:
b. You are given a 0-indexed array of integers nums of length n. You are initially positioned
at nums[0]. Each element nums[i] represents the maximum length of a forward jump from
index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: 0 <=
j <= nums[i] and i + j < n Return the minimum number of jumps to reach nums[n - 1]. The
test cases are generated such that you can reach nums[n - 1].

#include <vector>
using namespace std;
class Solution {
public:
int jump(vector<int>& nums) {
int numJumps = 0;
int k = 0;
int j = 0;

for (int i = 0; i < nums.size() - 1; ++i) {


k = max(k, i + nums[i]);
if (j == i) {
numJumps++;
j = k;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
}
}
return numJumps;
}
};

You might also like