Skip to content

Commit

Permalink
Added codes for 6 March
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanmay-312 committed Mar 6, 2024
1 parent 090508a commit dd14182
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 0 deletions.
101 changes: 101 additions & 0 deletions GeeksForGeeks/March/06-3-24/GFG.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//{ Driver Code Starts
//Initial Template for Java

import java.io.*;
import java.util.*;

class GFG
{
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
String s, patt;
s = sc.next();
patt = sc.next();

Solution ob = new Solution();

ArrayList<Integer> res = ob.search(patt, s);

for(int i = 0;i<res.size();i++)
System.out.print(res.get(i) + " ");
System.out.println();
}
}
}
// } Driver Code Ends


//User function Template for Java

class Solution
{
ArrayList<Integer> search(String pat, String txt)
{
// your code here
ArrayList<Integer> indices = new ArrayList<>();
int m = pat.length();
int n = txt.length();
int[] lps = computeLPSArray(pat);
int i = 0;
int j = 0;
while (i < n)
{
if (pat.charAt(j) == txt.charAt(i))
{
i++;
j++;
}
if (j == m)
{
indices.add(i - j + 1);
j = lps[j - 1];
}
else if (i < n && pat.charAt(j) != txt.charAt(i))
{
if (j != 0)
{
j = lps[j - 1];
}
else
{
i++;
}
}
}
return indices;
}


private int[] computeLPSArray(String pat)
{
int m = pat.length();
int[] lps = new int[m];
int len = 0;
for (int i = 1; i < m; )
{
if (pat.charAt(i) == pat.charAt(len))
{
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0)
{
len = lps[len - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
}
2 changes: 2 additions & 0 deletions GeeksForGeeks/March/06-3-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(|text| + |pattern|)
Space complexity - O(1)
2 changes: 2 additions & 0 deletions LeetCode/March/06-3-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n)
Space complexity - O(1)
29 changes: 29 additions & 0 deletions LeetCode/March/06-3-24/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution
{
public boolean hasCycle(ListNode head)
{
ListNode slow = head;
ListNode fast = head;

while (fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}

return false;
}
}

0 comments on commit dd14182

Please sign in to comment.