Skip to content

Commit 9e50c2f

Browse files
committed
2 parents c576abb + d4a1106 commit 9e50c2f

File tree

6 files changed

+340
-0
lines changed

6 files changed

+340
-0
lines changed

Arrays/Dutch-national-flag.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
// Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
3+
4+
// We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
5+
6+
// Input: nums = [2,0,2,1,1,0]
7+
// Output: [0,0,1,1,2,2]
8+
9+
// Time and space complexity of the solution
10+
11+
// Time complexity: O(n)
12+
// Space complexity: O(1)
13+
14+
15+
16+
17+
#include <bits/stdc++.h>
18+
using namespace std;
19+
20+
void sortColors(vector<int> &nums)
21+
{
22+
// created 3 variables start , low and end which are pointing start and low which are pointing to first index , end is pointing to last index .
23+
24+
int start = 0, low = 0, end = nums.size() - 1;
25+
while (low <= end)
26+
{
27+
if (nums[low] == 0) // checking if element of low is 0 . If yes then swap to start and low .
28+
{
29+
swap(nums[low], nums[start]);
30+
start++, low++;
31+
}
32+
else if (nums[low] == 1) // checking if element at low index is 1 , If yes then increase the index by 1 .
33+
{
34+
low++;
35+
}
36+
else // else swap the element of low index to end .
37+
{
38+
swap(nums[low], nums[end]);
39+
end--;
40+
}
41+
}
42+
}
43+
int main()
44+
{
45+
vector<int> nums{2, 0, 2, 1, 1, 0};
46+
sortColors(nums);
47+
48+
// Printing array's elements ..
49+
for (auto i : nums)
50+
{
51+
cout << i << " ";
52+
}
53+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/* Sure, here's a brief explanation of each solution:
2+
3+
Solution 1 (O(n) time, O(1) space):
4+
This solution uses Floyd's Tortoise and Hare algorithm to find the first duplicate value in the array.
5+
It initializes two pointers, a slow pointer and a fast pointer, to the first value in the array.
6+
The slow pointer moves one step at a time, while the fast pointer moves two steps at a time.
7+
When they meet at a certain point, it indicates that there is a cycle in the array.
8+
Then, the slow pointer is reset to the first value, and both pointers move one step at a time until they meet again,
9+
which is the start of the cycle (i.e., the first duplicate value in the array).
10+
11+
Solution 2 (O(n) time, O(n) space):
12+
This solution uses a HashSet to keep track of the integers that have been seen so far in the array.
13+
As the array is iterated over, each integer is checked to see if it is already in the set.
14+
If it is, then it is returned as the first integer that appears more than once.
15+
If no such integer is found, then -1 is returned. This solution has a time complexity of O(n) and a space complexity of O(n). */
16+
17+
// Solution 1: O(n) time and O(1) space
18+
public static int findDuplicate(int[] nums) {
19+
// iterate through the array
20+
for (int i = 0; i < nums.length; i++) {
21+
// calculate the absolute value of the current element
22+
int val = Math.abs(nums[i]);
23+
// check if the value at the calculated index is negative
24+
if (nums[val - 1] < 0) {
25+
// if it is, return the absolute value of the current element
26+
return val;
27+
}
28+
// otherwise, negate the value at the calculated index
29+
nums[val - 1] = -nums[val - 1];
30+
}
31+
// if no duplicate is found, return -1
32+
return -1;
33+
}
34+
35+
36+
// Solution 2: O(n) time and O(n) space solution:
37+
public static int findDuplicate(int[] nums) {
38+
// create a set to keep track of visited elements
39+
Set<Integer> visited = new HashSet<>();
40+
// iterate through the array
41+
for (int num : nums) {
42+
// check if the current element has already been visited
43+
if (visited.contains(num)) {
44+
// if it has, return the current element
45+
return num;
46+
}
47+
// otherwise, add it to the set of visited elements
48+
visited.add(num);
49+
}
50+
// if no duplicate is found, return -1
51+
return -1;
52+
}
53+
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'''
2+
This is an implementation of a singly linked list in Python with a Node class and a LinkedList class. The Node class represents each element of the linked list and the LinkedList class has methods to manipulate the list, including append, prepend, delete_node, and print_list.
3+
'''
4+
5+
class Node:
6+
def __init__(self, data):
7+
self.data = data
8+
self.next = None # The next node in the list
9+
10+
class LinkedList:
11+
def __init__(self):
12+
self.head = None # The first node in the list
13+
14+
def append(self, data):
15+
new_node = Node(data)
16+
if not self.head: # If the list is empty, set the new node as the head
17+
self.head = new_node
18+
return
19+
curr_node = self.head
20+
while curr_node.next: # Traverse to the last node in the list
21+
curr_node = curr_node.next
22+
curr_node.next = new_node # Set the next node of the last node to the new node
23+
24+
def prepend(self, data):
25+
new_node = Node(data)
26+
new_node.next = self.head # Set the next node of the new node to the current head
27+
self.head = new_node # Set the new node as the new head
28+
29+
def delete_node(self, data):
30+
if not self.head: # If the list is empty, do nothing
31+
return
32+
if self.head.data == data: # If the head is the node to delete, set the next node as the new head
33+
self.head = self.head.next
34+
return
35+
curr_node = self.head
36+
while curr_node.next: # Traverse the list until the last node
37+
if curr_node.next.data == data: # If the next node is the node to delete, set the next node of the current node to the node after the next node
38+
curr_node.next = curr_node.next.next
39+
return
40+
curr_node = curr_node.next
41+
42+
def print_list(self):
43+
curr_node = self.head
44+
while curr_node: # Traverse the list and print each node's data
45+
print(curr_node.data)
46+
curr_node = curr_node.next
47+

Linked List/middleOfTheLinkedList.cpp

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Given the head of a singly linked list, return the middle node of the linked list.
2+
// If there are two middle nodes, return the second middle node.
3+
4+
// Input: head = [1,2,3,4,5]
5+
// Output: [3,4,5]
6+
// Explanation: The middle node of the list is node 3.
7+
8+
// TIME ANS SPACE COMPLEXITY OF THE SOLUTION IS ::
9+
// Time complexity: O(n)
10+
// Space complexity: O(1)
11+
12+
#include <bits/stdc++.h>
13+
using namespace std;
14+
15+
// creating Node manualy
16+
class Node
17+
{
18+
public:
19+
int data;
20+
Node *next;
21+
22+
Node()
23+
{
24+
this->data = 0;
25+
this->next = NULL;
26+
}
27+
Node(int data)
28+
{
29+
this->data = data;
30+
this->next = NULL;
31+
}
32+
};
33+
34+
Node *middleNode(Node *head)
35+
{
36+
37+
Node *slow = head;
38+
Node *fast = head;
39+
40+
// Move slow pointer by one node at a time and fast pointer two nodes at a time.
41+
// While fast pointer reaches the end, slow pointer must have reached the middle node.
42+
43+
while (fast != NULL)
44+
{
45+
fast = fast->next;
46+
if (fast != NULL)
47+
{
48+
fast = fast->next;
49+
slow = slow->next;
50+
}
51+
}
52+
return slow; // return slow as ans
53+
}
54+
55+
int main()
56+
{
57+
// creating nodes.
58+
Node *first = new Node(1);
59+
Node *second = new Node(2);
60+
Node *third = new Node(3);
61+
Node *fourth = new Node(4);
62+
Node *fifth = new Node(5);
63+
64+
// head of linked list
65+
Node *head = first;
66+
67+
// Creating connection of nodes
68+
first->next = second;
69+
second->next = third;
70+
third->next = fourth;
71+
fourth->next = fifth;
72+
73+
cout << "The middle node of the list is node " << middleNode(head)->data << endl;
74+
return 0;
75+
}

Math/Find_Hamming_dis.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Example:
3+
Input: nums = [4,14,2]
4+
Output: 6
5+
6+
Explanation:
7+
In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
8+
showing the four bits relevant in this case).
9+
The answer will be:
10+
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
11+
12+
Detailed Explanation:
13+
The totalHammingDistance function takes a reference to a vector of integers nums, and returns the total Hamming distance between all possible pairs of elements in the vector.
14+
15+
In the function, we initialize the answer ans to 0, and the size of the vector n is obtained using the size() method of the vector. We then loop through all 32 bits (since we are dealing with 32-bit integers), and for each bit position i, we count the number of elements in nums with the i-th bit set by looping through all elements and checking if the bit is set using bitwise AND operator &.
16+
17+
The count c is then multiplied by (n-c), which gives the number of pairs with different bits at the i-th position. This count is added to the answer ans. Finally, the function returns the total Hamming distance.
18+
The main function is just an example usage, where we create a vector nums and call the totalHammingDistance method of a Solution object to get the total Hamming distance between all possible pairs of elements in nums.
19+
*/
20+
// code:
21+
22+
#include<iostream>
23+
#include <vector>
24+
25+
using namespace std;
26+
27+
class Solution {
28+
public:
29+
int totalHammingDistance(vector<int>& nums) {
30+
int ans = 0;
31+
int n = nums.size();
32+
for(int i = 0; i < 32; i++) {
33+
int c = 0;
34+
for(int j = 0; j < n; j++) {
35+
if((nums[j] & (1 << i))) {
36+
c++;
37+
}
38+
}
39+
ans += (c * (n - c));
40+
}
41+
return ans;
42+
}
43+
};
44+
45+
int main() {
46+
// Example usage
47+
vector<int> nums = {4, 14, 2};
48+
Solution s;
49+
int result = s.totalHammingDistance(nums);
50+
return 0;
51+
}
52+
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/* PROBLEM STATEMENT */
2+
3+
/* Given an array of integers between 1 and n, inclusive, where n is the length of the array,
4+
write a function that returns the first integer that appears more than once (when the array
5+
is read from left to right).
6+
*/
7+
8+
9+
10+
/* The difference between the two solutions provided is that the first solution has a space complexity
11+
of 0(1), meaning constant space complexity, while the second solution has a space complexity of 0(n),
12+
meaning linear space complexity. finally both solutions has a time complexity of 0(n), meaning linear
13+
time complexity.
14+
*/
15+
16+
17+
18+
// Big-O = O(n) time complexity
19+
// Big-O = O(1) space complexity
20+
const firstDuplicate1 = arr => {
21+
22+
// firstly iterate/loop through the given array
23+
for(let i = 0; i < arr.length; i++){
24+
// then use the Array.prototype.lastIndexOf() method to check for duplicates.
25+
// finally return the first number that appers more than once.
26+
if(arr.lastIndexOf(arr[i]) !== i) return arr[i];
27+
};
28+
29+
// return the message No duplicate found, if no dupliacte is found after the iteration process.
30+
return "No duplicate found!";
31+
}
32+
33+
console.log(firstDuplicate1([2, 1, 5, 2, 3, 3, 4]));
34+
35+
36+
37+
38+
// Big-O = O(n) time complexity
39+
// Big-O = O(n) space complexity
40+
const firstDuplicate2 = arr => {
41+
42+
// first off, let's create our Set object
43+
// this Set object will allow us to store each element from the given array as a unique value
44+
let elementSet = new Set();
45+
46+
// then iterate/loop through the given array
47+
for (let i = 0; i < arr.length; i++) {
48+
// we'll check to see if the Set already contains the element that we're currently on in our loop
49+
// if it exists, then we've found our first duplicate! We'll return that value and be done
50+
if (elementSet.has(arr[i])) return arr[i];
51+
// if the element isn't in our Set yet, then we add it to the Set and move on to the next element in the array.
52+
elementSet.add(arr[i]);
53+
}
54+
55+
// return the message No duplicate found, if no dupliacte is found after the iteration process.
56+
return "No duplicates found!";
57+
}
58+
59+
console.log(firstDuplicate2([2, 1, 5, 2, 3, 3, 4]));
60+

0 commit comments

Comments
 (0)