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

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 1.1

Student Name: Amit Kumar UID: 21BCS7024


Branch: CSE Section/Group: 640-B
Semester: 6th Date of Performance:15-01-24
Subject Name:Advance Programming Lab-2 Subject Code: 21CSP-351

1. Aim:
To implement the concept of Arrays, Queues and Stack and Linked List.

2. Objective:

A) 3Sum: 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.

B) Merge Two Sorted Lists: You are given the heads of two sorted linked
lists list1 and list2. Merge the two lists into one sorted list. The list should
be made by splicing together the nodes of the first two lists. Return the head of
the merged linked list.

3. Script and Output:

A. 3Sum

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
if (nums.size() < 3)
return {};
vector<vector<int>> ans;
ranges::sort(nums);
or (int i = 0; i + 2 < nums.size(); ++i) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
int l = i + 1;

Amit Kumar 21BCS7024


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
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])
--r;
} else if (sum < 0) {
++l;
} else {
--r;
}
}
}
return ans;
}
};

OUTPUT:

Amit Kumar 21BCS7024


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

B. Merge Two Sorted Lists


class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if (!list1 || !list2)
return list1 ? list1 : list2;
if (list1->val > list2->val)
swap(list1, list2);
list1->next = mergeTwoLists(list1->next, list2);
return list1;
}
};

Amit Kumar 21BCS7024

You might also like