diff --git a/GeeksForGeeks/March/07-3-24/GFG.java b/GeeksForGeeks/March/07-3-24/GFG.java new file mode 100644 index 0000000..88af2b3 --- /dev/null +++ b/GeeksForGeeks/March/07-3-24/GFG.java @@ -0,0 +1,58 @@ +//{ Driver Code Starts +//Initial Template for Java + +import java.io.*; +import java.util.*; + +class GFG { + public static void main(String args[]) throws IOException { + BufferedReader read = + new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(read.readLine()); + while (t-- > 0) { + int N = Integer.parseInt(read.readLine()); + String S = read.readLine(); + + Solution ob = new Solution(); + System.out.println(ob.longestSubstring(S, N)); + } + } +} + +// } Driver Code Ends + + +//User function Template for Java + +class Solution +{ + static String longestSubstring(String s, int n) + { + // code here + int[][] dp = new int[n + 1][n + 1]; + int max = 0; + int index = 0; + + for(int i = 1; i <= n ; i++) + { + for(int j = i + 1; j <= n; j++) + { + if(s.charAt(i - 1) == s.charAt(j - 1) && j - i > dp[i - 1][j - 1]) + { + dp[i][j] = dp[i - 1][j - 1] + 1; + + if(dp[i][j] > max) + { + max = dp[i][j]; + index = Math.max(i, index); + } + } + + else + dp[i][j] = 0; + } + } + + return max > 0 ? s.substring(index - max, index ) : "-1"; + } +}; diff --git a/GeeksForGeeks/March/07-3-24/README.md b/GeeksForGeeks/March/07-3-24/README.md new file mode 100644 index 0000000..b4189b7 --- /dev/null +++ b/GeeksForGeeks/March/07-3-24/README.md @@ -0,0 +1,2 @@ +Time complexity - O(n^2) +Space complexity - O(n^2) diff --git a/LeetCode/March/07-3-24/README.md b/LeetCode/March/07-3-24/README.md new file mode 100644 index 0000000..9567f26 --- /dev/null +++ b/LeetCode/March/07-3-24/README.md @@ -0,0 +1,2 @@ +Time complexity - O(n) +Space complexity - O(1) diff --git a/LeetCode/March/07-3-24/Solution.java b/LeetCode/March/07-3-24/Solution.java new file mode 100644 index 0000000..aae6049 --- /dev/null +++ b/LeetCode/March/07-3-24/Solution.java @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution +{ + public ListNode middleNode(ListNode head) + { + if (head==null) + return null; + + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + + return slow; + } +}