Skip to content

[Hacker Rank] Interview Preparation Kit: Linked Lists: Detect a Cycle… #80

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
Jun 22, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
namespace algorithm_exercises_csharp.hackerrank.interview_preparation_kit;

[TestClass]
public class LinkedListCycleTest
{
class LinkedListCycleTestCase
{
public string title = "";
public LinkedList.Node? llist;
public bool expected;
}

private static LinkedListCycleTestCase[] tests = [];

[TestInitialize]
public void testInitialize()
{
// Linked list sample data:
LinkedList.Node ll1_1 = new(1);
LinkedList.Node ll1_2 = new(2);
LinkedList.Node ll1_3 = new(3);
LinkedList.Node ll1_4 = new(4);
LinkedList.Node ll1_5 = new(5);

ll1_1.next = ll1_2;
ll1_2.next = ll1_3;
ll1_3.next = ll1_4;
ll1_4.next = ll1_5;
ll1_4.next = ll1_3; // <- cycle

LinkedList.Node ll2_1 = new(1);
LinkedList.Node ll2_2 = new(2);
LinkedList.Node ll2_3 = new(3);

ll2_1.next = ll2_2;
ll2_2.next = ll2_3;

tests = [
new()
{
title = "Sample Test case X",
llist = ll1_1,
expected = true
},
new()
{
title = "Sample Test case Y",
llist = ll2_1,
expected = false
}
];
}

[TestMethod]
public void testLinkedListCycle()
{
bool result;

foreach (LinkedListCycleTestCase test in tests)
{
result = LinkedListCycle.hasCycle(test.llist);
Assert.AreEqual(
test.expected,
result,
String.Format(
"{0} testLinkedListCycle({1}) => must be: {2}",
test.title,
test.llist,
test.expected
)
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
namespace algorithm_exercises_csharp.hackerrank.interview_preparation_kit;

[TestClass]
public class NodeTest
{
class NodeTestCase
{
public string title = "";
public LinkedList.Node? llist;
public string separator = "";
public string expected = "";
}

private static NodeTestCase[] tests = [];

[TestInitialize]
public void testInitialize()
{
// Linked list sample data:
LinkedList.Node ll1_1 = new(1);
LinkedList.Node ll1_2 = new(2);
LinkedList.Node ll1_3 = new(3);
LinkedList.Node ll1_4 = new(4);
LinkedList.Node ll1_5 = new(5);

ll1_1.next = ll1_2;
ll1_2.next = ll1_3;
ll1_3.next = ll1_4;
ll1_4.next = ll1_5;

tests = [
new()
{
title = "Sample Test case X",
llist = ll1_1,
separator = ", ",
expected = "1, 2, 3, 4, 5"
}
];
}

[TestMethod]
public void testPrintLinkedList()
{
foreach (NodeTestCase test in tests)
{
StringWriter sw = new();

LinkedList.printSinglyLinkedList(test.llist, test.separator, sw);

string result = sw.ToString();
Assert.AreEqual(
test.expected,
result,
String.Format(
"{0} testPrintLinkedList(<Node>, {1}, <Textwriter>) => must be: {2}",
test.title,
test.separator,
test.expected
)
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// @link Problem definition [[docs/hackerrank/interview_preparation_kit/linked_lists/ctci_linked_list_cycle.md]]

namespace algorithm_exercises_csharp.hackerrank.interview_preparation_kit;

using System.Diagnostics.CodeAnalysis;

public class LinkedListCycle
{
[ExcludeFromCodeCoverage]
protected LinkedListCycle() { }

public static bool hasCycle(LinkedList.Node? head)
{
List<LinkedList.Node> llindex = [];

LinkedList.Node? node = head;

while (node != null)
{
if (llindex.Contains(node))
{
return true;
}

llindex.Add(node);
node = node.next;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace algorithm_exercises_csharp.hackerrank.interview_preparation_kit;

public class LinkedList
{
public class Node(int nodeData)
{
public int data { get; set; } = nodeData;
public Node? next { get; set; } = null;
}

public static void printSinglyLinkedList(Node? node, string sep, TextWriter textWriter)
{
Node? pointTo = node;

while (pointTo != null)
{
textWriter.Write(pointTo.data);

pointTo = pointTo.next;

if (pointTo != null)
{
textWriter.Write(sep);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# [Linked Lists: Detect a Cycle](https://www.hackerrank.com/challenges/ctci-linked-list-cycle)

- Difficulty: `#easy`
- Category: `#ProblemSolvingIntermediate`

A linked list is said to contain a cycle if any node is visited more
than once while traversing the list.
For example, in the following graph there is a cycle formed
when node `5` points back to node `3`.

```mermaid
flowchart LR

1([1])
2([2])
3([3])
4([4])
5([5])

1 --> 2
2 --> 3
3 --> 4
4 --> 5
5 --> 3

classDef default color:#000,fill:#97FE9C,stroke:#488A53,stroke-width:4px;
```

## Function Description

Complete the function has_cycle in the editor below.
It must return a boolean true if the graph contains a cycle, or false.

has_cycle has the following parameter(s):

- head: a pointer to a Node object that points to the head of a linked list.

## Returns

- boolean: True if there is a cycle, False if there is not

**Note**: If the list is empty, `head` will be null.

## Input Format

There is no input for this challenge.
A random linked list is generated at runtime and passed to your function.

## Constraints

- $ 0 \leq \text{list size} \leq 100$

## Sample Input

The following linked lists are passed as arguments to your function:

```mermaid
flowchart LR

1([1])
1 --> NULL

classDef default color:#000,fill:#97FE9C,stroke:#488A53,stroke-width:4px;

classDef none color: #DDD, fill:#FFFFFF00,fill:#FFFFFF00, stroke:#FFFFFF00, stroke-width: 0;

class NULL none
```

```mermaid
flowchart LR

1([1])
2([2])
3([3])

1 --> 2
2 --> 3
3 --> 2

classDef default color:#000,fill:#97FE9C,stroke:#488A53,stroke-width:4px;

classDef none color: #DDD, fill:#FFFFFF00,fill:#FFFFFF00, stroke:#FFFFFF00, stroke-width: 0;

class NULL none
```

## Sample Output

```text
0
1
```

## Explanation

1. The first list has no cycle, so we return false and the
hidden code checker prints 0 to stdout.
2. The second list has a cycle, so we return true and the
hidden code checker prints 1 to stdout.