Skip to content

solution added to 415 #3868

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions dsa-solutions/gfg-solutions/Easy problems/square-root.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
---
id: square-root
title: Square Root
sidebar_label: Square-Root
sidebar_label: 9 Square Root
tags:
- Math
- Binary Search
description: "This document provides solutions to the problem of finding the Square Root of an integer."
- Python
- Java
- C++
- JavaScript
- TypeScript
description: "This document provides solutions to the problem of finding the square root of a given integer using various programming languages."
---

## Problem
Expand Down Expand Up @@ -38,7 +43,7 @@ You don't need to read input or print anything. The task is to complete the func
**Expected Auxiliary Space:** $O(1)$

**Constraints**
- `1 ≤ x ≤ 10^7`
- $1 ≤ x ≤ 10^7$

## Solution

Expand Down Expand Up @@ -185,4 +190,11 @@ class Solution {
The provided solutions efficiently find the floor value of the square root of a given integer `x` using binary search. This approach ensures a time complexity of $ O(log N) and an auxiliary space complexity of $O(1)$. The algorithms are designed to handle large values of `x` up to 10^7 efficiently without relying on built-in square root functions.

**Time Complexity:** $O(log N)$
**Auxiliary Space:** $O(1)$
**Auxiliary Space:** $O(1)$

---

## References

- **GeeksforGeeks Problem:** [Square root](https://www.geeksforgeeks.org/problems/square-root/0)
- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/)
Original file line number Diff line number Diff line change
@@ -1,169 +1,227 @@
---

id: copy-list-with-random-pointer
title: Copy List with Random Pointer
sidebar_label: 0138 Copy List with Random Pointer
title: Copy List With Random Pointer
level: medium
sidebar_label: Copy List With Random Pointer
tags:
- Hash Table
- Linked List
- Java
- Python
- C++
- JavaScript

description: "This is a solution to the Copy List with Random Pointer problem on LeetCode."
description: "This document provides solutions for the Copy List With Random Pointer problem on LeetCode."

---

## Problem Description

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.

Construct a deep copy of the list. The deep copy should consist of exactly `n` brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Construct a deep copy of the list.

### Examples

**Example 1:**

![e1](https://github.com/user-attachments/assets/af16a7ff-3439-4683-8f77-9fdbb3332bef)

```
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
```

**Example 2:**

![e2](https://github.com/user-attachments/assets/f805c77f-c6cd-4b92-9f9a-c17665bfa317)

```
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
```

**Example 3:**
```
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
```

---
### Constraints:

## Solution for Copy List with Random Pointer
- The number of nodes in the list is in the range [0, 1000].
- `-10000 <= Node.val <= 10000`
- Node.random is null or is pointing to a node in the linked list.

---

### Understand the Problem:
## Approach to Solve the Copy List with Random Pointer Problem

Create a deep copy of a linked list where each node has a `next` and a `random` pointer. The new list should be identical in structure to the original, but with all new nodes. Ensure the `random` pointers in the new list accurately reflect the original's `random` pointer relationships.
To create a deep copy of a linked list with an additional random pointer, follow these steps:

### Approach

1. **Interweaving Nodes**: Create and insert new nodes immediately after each original node, forming an interwoven list.
2. **Assigning Random Pointers**: Set the `random` pointers of the new nodes based on the `random` pointers of the original nodes.
3. **Separating Lists**: Restore the original list and extract the copied list by adjusting the `next` pointers of both original and new nodes.
1. **Create Clones Adjacent to Original Nodes:**
- Iterate through the original list and create a new node for each original node. Insert this new node right next to the original node. This way, each original node will have its clone right next to it.

2. **Assign Random Pointers to Cloned Nodes:**
- Iterate through the list again. For each original node, if it has a random pointer, set the random pointer of the clone node to point to the clone of the node that the original node’s random pointer is pointing to. This can be achieved because the clone of any node `A` is next to `A`.

3. **Restore the Original List and Extract the Cloned List:**
- Iterate through the list once more to restore the original list by separating the original nodes from their clones. Extract the cloned list by linking the cloned nodes together.

#### Code in Different Languages

<Tabs>


<TabItem value="Python" label="Python" default>
### C++
```cpp
class Node {
public:
int val;
Node* next;
Node* random;

Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};

class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;

// Step 1: Create a new node for each original node and insert it next to the original node.
Node* curr = head;
while (curr) {
Node* newNode = new Node(curr->val);
newNode->next = curr->next;
curr->next = newNode;
curr = newNode->next;
}

<SolutionAuthor name="sivaprasath2004"/>
// Step 2: Assign random pointers for the new nodes.
curr = head;
while (curr) {
if (curr->random) {
curr->next->random = curr->random->next;
}
curr = curr->next->next;
}

```python
// Step 3: Restore the original list and extract the copied list.
curr = head;
Node* copiedHead = head->next;
Node* copiedCurr = copiedHead;
while (curr) {
curr->next = curr->next->next;
if (copiedCurr->next) {
copiedCurr->next = copiedCurr->next->next;
}
curr = curr->next;
copiedCurr = copiedCurr->next;
}

class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = x
self.next = next
self.random = random
return copiedHead;
}
};
```

def copyRandomList(head: 'Node') -> 'Node':
if not head:
return None

current = head
while current:
new_node = Node(current.val, current.next, None)
current.next = new_node
current = new_node.next

current = head
while current:
if current.random:
current.next.random = current.random.next
current = current.next.next

original = head
copy = head.next
copy_head = copy

while original:
original.next = original.next.next
if copy.next:
copy.next = copy.next.next
original = original.next
copy = copy.next

return copy_head

```
</TabItem>

<TabItem value="Js" label="JavaScript" default>

<SolutionAuthor name="sivaprasath2004"/>

```JS
### Java
```java
class Node {
constructor(val, next = null, random = null) {
int val;
Node next;
Node random;

public Node(int val) {
this.val = val;
this.next = next;
this.random = random;
this.next = null;
this.random = null;
}
}

function copyRandomList(head) {
if (!head) return null;

let current = head;
while (current) {
const newNode = new Node(current.val);
newNode.next = current.next;
current.next = newNode;
current = newNode.next;
}

current = head;
while (current) {
if (current.random) {
current.next.random = current.random.next;
class Solution {
public Node copyRandomList(Node head) {
if (head == null) return null;

// Step 1: Create a new node for each original node and insert it next to the original node.
Node curr = head;
while (curr != null) {
Node newNode = new Node(curr.val);
newNode.next = curr.next;
curr.next = newNode;
curr = newNode.next;
}
current = current.next.next;
}
current = head;
const newHead = head.next;
let copyCurrent = newHead;

while (current) {
current.next = current.next.next;
if (copyCurrent.next) {
copyCurrent.next = copyCurrent.next.next;

// Step 2: Assign random pointers for the new nodes.
curr = head;
while (curr != null) {
if (curr.random != null) {
curr.next.random = curr.random.next;
}
curr = curr.next.next;
}
current = current.next;
copyCurrent = copyCurrent.next;
}

return newHead;
}
// Step 3: Restore the original list and extract the copied list.
curr = head;
Node copiedHead = head.next;
Node copiedCurr = copiedHead;
while (curr != null) {
curr.next = curr.next.next;
if (copiedCurr.next != null) {
copiedCurr.next = copiedCurr.next.next;
}
curr = curr.next;
copiedCurr = copiedCurr.next;
}

return copiedHead;
}
}
```
</TabItem>

</Tabs>


### Output
### Python
```python
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = x
self.next = next
self.random = random

![Screenshot from 2024-07-19 21-11-44](https://github.com/user-attachments/assets/2c2a7efb-711d-4f6e-aebd-8f540de015c3)
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None

# Step 1: Create a new node for each original node and insert it next to the original node.
curr = head
while curr:
newNode = Node(curr.val)
newNode.next = curr.next
curr.next = newNode
curr = newNode.next

# Step 2: Assign random pointers for the new nodes.
curr = head
while curr:
if curr.random:
curr.next.random = curr.random.next
curr = curr.next.next

# Step 3: Restore the original list and extract the copied list.
curr = head
copiedHead = head.next
copiedCurr = copiedHead
while curr:
curr.next = curr.next.next
if copiedCurr.next:
copiedCurr.next = copiedCurr.next.next
curr = curr.next
copiedCurr = copiedCurr.next

return copiedHead
```

### Complexity

- **Time Complexity:** O(n), where `n` is the number of nodes in the linked list. The algorithm iterates through the list three times: once for interweaving nodes, once for setting random pointers, and once for separating the lists.
- **Time Complexity:** $O(n)$ - Each of the three steps involves a single pass through the list.
- **Space Complexity:** $O(1)$ - The space complexity is constant as we are not using any additional data structures for storage.

- **Space Complexity:** O(1), since the algorithm uses a constant amount of extra space beyond the input list itself (e.g., pointers for traversal and temporary variables).
### Summary

This approach efficiently creates a deep copy of a linked list with random pointers by leveraging the existing structure of the list and ensuring that each node and its clone are linked adjacently.
Loading
Loading