0% found this document useful (0 votes)
2 views27 pages

Skill Lab

The document is a skill lab assignment for a Bachelor of Engineering in Computer Science and Engineering at Visvesvaraya Technological University. It includes various programming examples and solutions related to data structures such as maps, linked lists, trees, binary search trees, stacks, queues, heaps, graphs, and algorithms for searching, sorting, and recursion. The assignment is submitted by Sushmitha Reddy B under the guidance of Dr. Pampapathi B. M.
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)
2 views27 pages

Skill Lab

The document is a skill lab assignment for a Bachelor of Engineering in Computer Science and Engineering at Visvesvaraya Technological University. It includes various programming examples and solutions related to data structures such as maps, linked lists, trees, binary search trees, stacks, queues, heaps, graphs, and algorithms for searching, sorting, and recursion. The assignment is submitted by Sushmitha Reddy B under the guidance of Dr. Pampapathi B. M.
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/ 27

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

JNANA SANGAMA, BELAGAVI – 590018

“SKILL LAB ASSIGNMENT”

BACHELOR OF ENGINEERING
In
COMPUTER SCIENCE & ENGINEERING
Submitted by

NAME:SUSHMITHA REDDY.B

Under the guidance of


DR.PAMPAPATHI.B.M

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

RAO BAHADUR Y. MAHABALESWARAPPA ENGINEERING COLLEGE


BALLARI- 583 104 2024-25
MAPS OR DICTIONARIES
#include <iostream>

#include <map>

#include <string>

int main()

std::map<std::string, std::string> phoneBook;

int n;

std::cin >> n;

for (int i = 0; i < n; ++i)

std::string name, number;

std::cin >> name >> number;

phoneBook[name] = number;

std::string query;

while (std::cin >> query)

if (phoneBook.find(query) != phoneBook.end())

std::cout << query << "=" << phoneBook[query] << std::endl;

else

std::cout << "Not found" << std::endl;


}

return 0;

}
LINKED LIST

class Node:

def _init_(self, data):

self.data = data

self.next = None

class LinkedList:

def _init_(self):

self.head = None

def append(self, data):

if not self.head:

self.head = Node(data)

else:

curr = self.head

while curr.next:

curr = curr.next

curr.next = Node(data)

class Solution:

def isLengthEven(self, head):

count = 0

current = head

while current:

count += 1

current = current.next
return count % 2 == 0

llist = LinkedList()

for value in [12, 52, 10, 47, 95, 0]:

llist.append(value)

flag = Solution().isLengthEven(llist.head)

print(flag)
TRESS

SAME TREE

class Solution {

public:

bool isSameTree(TreeNode* p, TreeNode* q) {

// If both nodes are null, they are the same

if (!p && !q) return true;

// If one of them is null or values don't match, trees aren't the same

if (!p || !q || p->val != q->val) return false;

// Recursively check left and right subtrees

return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);

} };
BINARY SEARCH TREE

def checkBST(root):

def isBST(node, minVal, maxVal):

if node is None:

return True

if not (minVal < node.data < maxVal):

return False

return (isBST(node.left, minVal, node.data) and

isBST(node.right, node.data, maxVal))

return isBST(root, float('-inf'), float('inf'))


REPLACE WORDS

class Solution {

public:

string replaceWords(vector<string>& dictionary, string sentence) {

unordered_set<string> dict(dictionary.begin(), dictionary.end()); // Fast

lookup

stringstream ss(sentence), result;

string word;

while (ss >> word) { // Split sentence into words

string prefix = "";

for (int i = 1; i <= word.length(); ++i) {

prefix = word.substr(0, i);

if (dict.count(prefix)) break; // Stop at first matching prefix

result << (dict.count(prefix) ? prefix : word) << " "; // Use root if found

string res = result.str();

res.pop_back(); // remove trailing space

return res;

};
STACKS AND QUEUES
VALID PARENTHESIS

class Solution {

public:

bool isValid(string s) {

stack<char> stk;

for (char c : s) {

if (c == '(' || c == '{' || c == '[') {

stk.push(c);

} else {

if (stk.empty()) return false;

char top = stk.top();

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

(c == '}' && top != '{') ||

(c == ']' && top != '[')) {

return false;

stk.pop();
HEAPS
QHEAP1

import java.io.*;

import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int Q = sc.nextInt(); // Number of queries

PriorityQueue<Integer> minHeap = new PriorityQueue<>();

HashSet<Integer> elements = new HashSet<>(); // To maintain distinct elements

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

int queryType = sc.nextInt();

if (queryType == 1) {

int x = sc.nextInt();

if (elements.add(x)) { // Only add if not already present

minHeap.add(x);

} else if (queryType == 2) {

int x = sc.nextInt();

if (elements.remove(x)) {

minHeap.remove(x); // Remove specific element


}

} else if (queryType == 3) {

System.out.println(minHeap.peek());

}
Top K Frequent Words

import java.util.*;

class Solution {

public List<String> topKFrequent(String[] words, int k) {

// Step 1: Count frequency

Map<String, Integer> freqMap = new HashMap<>();

for (String word : words) {

freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);

// Step 2: Min-heap with custom comparator

PriorityQueue<String> heap = new PriorityQueue<>(

(a, b) -> freqMap.get(a).equals(freqMap.get(b)) ?

b.compareTo(a) : freqMap.get(a) - freqMap.get(b)

);

for (String word : freqMap.keySet()) {

heap.offer(word);

if (heap.size() > k) {

heap.poll(); // Remove least frequent

// Step 3: Extract from heap and reverse

List<String> result = new ArrayList<>();

while (!heap.isEmpty()) {

result.add(heap.poll());

}
Collections.reverse(result); // Highest frequency first

return result;

}
GRAPHS
COURSE SCHEDULE

public class Solution {

public int[] findOrder(int numCourses, int[][] prerequisites) {

List[] graph = new ArrayList[numCourses];

int[] inDegree = new int[numCourses];

// Initialize adjacency list

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

graph[i] = new ArrayList<>();

// Build the graph and in-degree array

for (int[] pair : prerequisites) {

int course = pair[0];

int prereq = pair[1];

graph[prereq].add(course);

inDegree[course]++;

// Queue for all courses with no prerequisites

Queue<integer> queue = new LinkedList<>();

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

if (inDegree[i] == 0) {

queue.offer(i);

int[] order = new int[numCourses];


int index = 0;

// Process courses

while (!queue.isEmpty()) {

int course = queue.poll();

order[index++] = course;

for (int next : graph[course]) {

inDegree[next]--;

if (inDegree[next] == 0) {

queue.offer(next);

// Check if topological sort is possible (no cycle)

return index == numCourses ? order : new int[0];

}
REDUNDANT CONNECTION

public class Solution {

public int[] findRedundantConnection(int[][] edges) {

int n = edges.length;

int[] parent = new int[n + 1];

// Initialize parent array

for (int i = 1; i <= n; i++) {

parent[i] = i;

for (int[] edge : edges) {

int u = edge[0];

int v = edge[1];

// Find roots

int pu = find(parent, u);

int pv = find(parent, v);

// If both have same root, this edge creates a cycle

if (pu == pv) {

return edge;

// Union

parent[pu] = pv;

return new int[0]; // Just a fallback (problem guarantees one answer)

private int find(int[] parent, int x) {


if (parent[x] != x) {

parent[x] = find(parent, parent[x]); // Path compression

return parent[x];

}
RUNTIME ANALYSIS
SEARCHING AND SORTING
RECURSION AND DP
CLIMBING STAIRS

class Solution {

public int climbStairs(int n) {

if (n <= 1) return 1;

int a = 1, b = 1;

for (int i = 2; i <= n; i++) {

int temp = a + b;

a = b;

b = temp;

return b;

}
GREATEST COMMON DIVISOR

public class Solution {

public int gcd(int A, int B) {

// Debug: print initial values

System.out.println("Starting values: A = " + A + ", B = " + B);

while (A != 0 && B != 0) {

if (A > B) {

A = A - B;

System.out.println("A > B, new A = " + A);

} else {

B = B - A;

System.out.println("B >= A, new B = " + B);

int result = (A == 0) ? B : A;

System.out.println("Final GCD = " + result)


return result;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy