❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

POTD #22 – Longest substring with distinct characters | Geeks For Geeks

11 January 2025 at 16:44

Problem Statement

Geeks For Geeks : https://www.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1

Given a string s, find the length of the longest substring with all distinct characters.Β 


Input: s = "geeksforgeeks"
Output: 7
Explanation: "eksforg" is the longest substring with all distinct characters.


Input: s = "abcdefabcbb"
Output: 6
Explanation: The longest substring with all distinct characters is "abcdef", which has a length of 6.

My Approach – Sliding Window


class Solution:
    def longestUniqueSubstr(self, s):
        # code here
        char_index = {}
        max_length = 0
        start = 0
        
        for i, char in enumerate(s):
            if char in char_index and char_index[char] >= start:
                start = char_index[char] + 1 #crux
            
            char_index[char] = i
            
            max_length = max(max_length, i - start + 1)
        
        return max_length
                

POTD #19 – Count the number of possible triangles | Geeks For Geeks

8 January 2025 at 15:08

Problem Statement

Geeks For Geeks – https://www.geeksforgeeks.org/problems/count-possible-triangles-1587115620/1

Given an integer array arr[]. Find the number of triangles that can be formed with three different array elements as lengths of three sides of the triangle.Β  A triangle with three given sides is only possible if sum of any two sides is always greater than the third side.


Input: arr[] = [4, 6, 3, 7]
Output: 3
Explanation: There are three triangles possible [3, 4, 6], [4, 6, 7] and [3, 6, 7]. Note that [3, 4, 7] is not a possible triangle.  


Input: arr[] = [10, 21, 22, 100, 101, 200, 300]
Output: 6
Explanation: There can be 6 possible triangles: [10, 21, 22], [21, 100, 101], [22, 100, 101], [10, 100, 101], [100, 101, 200] and [101, 200, 300]

My Approach


class Solution:
    #Function to count the number of possible triangles.
    def countTriangles(self, arr):
        # code here
        arr.sort()
        n = len(arr)
        cnt = 0
        for itr in range(2, n):
            left = 0
            right = itr - 1
            
            while left < right:
                
                if arr[left] + arr[right] > arr[itr]:
                    cnt += right - left
                    right -= 1
                else:
                    left += 1
        return cnt

POTD #16 – Count Pairs whose sum is less than target | Geeks For Geeks

5 January 2025 at 17:13

Problem Statement

Geeks For Geeks : https://www.geeksforgeeks.org/problems/count-pairs-whose-sum-is-less-than-target/1

Given an arrayΒ arr[]Β and an integerΒ target.Β You have to find the number of pairs in the array whose sum is strictly less than theΒ target.


Input: arr[] = [7, 2, 5, 3], target = 8
Output: 2
Explanation: There are 2 pairs with sum less than 8: (2, 5) and (2, 3). 


Input: arr[] = [5, 2, 3, 2, 4, 1], target = 5
Output: 4
Explanation: There are 4 pairs whose sum is less than 5: (2, 2), (2, 1), (3, 1) and (2, 1).

My Approach

Sorted the array and used two pointer approach to find the possible pairs.


class Solution:
    #Complete the below function
    def countPairs(self, arr, target):
        #Your code here
        arr.sort()
        n = len(arr)
        cnt = 0
        left = 0
        right = n - 1
        while right > left:
            if arr[right] + arr[left] < target:
                cnt += right - left
                left += 1
            elif arr[right] + arr[left] >= target:
                right -= 1
            
        return cnt
                    

POTD #15 – Count all triplets with given sum in sorted array | Geeks For Geeks

4 January 2025 at 18:14

Problem Statement

Geeks For Geeks : https://www.geeksforgeeks.org/problems/count-all-triplets-with-given-sum-in-sorted-array/1

Given a sorted arrayΒ arr[] and a target value, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k.


Input: arr[] = [-3, -1, -1, 0, 1, 2], target = -2
Output: 4
Explanation: Two triplets that add up to -2 are:
arr[0] + arr[3] + arr[4] = (-3) + 0 + (1) = -2
arr[0] + arr[1] + arr[5] = (-3) + (-1) + (2) = -2
arr[0] + arr[2] + arr[5] = (-3) + (-1) + (2) = -2
arr[1] + arr[2] + arr[3] = (-1) + (-1) + (0) = -2


Input: arr[] = [-2, 0, 1, 1, 5], target = 1
Output: 0
Explanation: There is no triplet whose sum is equal to 1. 

My Approach:

Initially i tried to approach the problem, similar to this. All testcases but 1 passed. Initial time complexity is O(n3). Failed 6 times.



class Solution:
    def countTriplets(self, arr, target):
        hash_set = {}
        total = len(arr)
        cnt = 0
        
        # Build the hash_set with indices for each value in arr
        for i in range(total):
            if arr[i] not in hash_set:
                hash_set[arr[i]] = []
            hash_set[arr[i]].append(i)
        
        # Iterate through all pairs (itr, jtr)
        for itr in range(total):
            for jtr in range(itr + 1, total):
                rem = target - arr[itr] - arr[jtr]
                
                # Check for remaining value in hash_set
                if rem in hash_set:
                    # Use binary search to count indices greater than jtr
                    indices = hash_set[rem]
                    low, high = 0, len(indices)
                    
                    while low < high:
                        mid = (low + high) // 2
                        if indices[mid] > jtr:
                            high = mid
                        else:
                            low = mid + 1
                    
                    cnt += len(indices) - low

        return cnt






Then after reading blogs, switched to Two Pointer method



class Solution:
    def countTriplets(self, arr, target):
        n = len(arr)
        res = 0
 
        for i in range(n - 2):
            left = i + 1
            right = n - 1

            while left < right:
                sum = arr[i] + arr[left] + arr[right]
    
                if sum < target:
                    left += 1
    
                elif sum > target:
                    right -= 1
    
                else:
                    ele1 = arr[left]
                    ele2 = arr[right]
                    cnt1 = 0
                    cnt2 = 0
    
                    while left <= right and arr[left] == ele1:
                        left += 1
                        cnt1 += 1
    
                    while left <= right and arr[right] == ele2:
                        right -= 1
                        cnt2 += 1

                    if ele1 == ele2:
                        res += (cnt1 * (cnt1 - 1)) // 2
                    else:
                        res += (cnt1 * cnt2)
    
        return res






POTD #11 – Longest Consecutive Subsequence | Geeks For Geeks

31 December 2024 at 17:43

Problem Statement

Geeks For Geeks – https://www.geeksforgeeks.org/problems/longest-consecutive-subsequence2449/1

Given an array arr[] of non-negative integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.


Input: arr[] = [2, 6, 1, 9, 4, 5, 3]
Output: 6
Explanation: The consecutive numbers here are 1, 2, 3, 4, 5, 6. These 6 numbers form the longest consecutive subsquence.


Input: arr[] = [1, 9, 3, 10, 4, 20, 2]
Output: 4
Explanation: 1, 2, 3, 4 is the longest consecutive subsequence.

My Approach

1. Sort the array.Initialize two variables:

  • max_sequence to 1 (to store the length of the longest consecutive subsequence).
  • cont_sub_sequence to 1 (to track the current consecutive subsequence length).

2. Loop through the array starting from the second element:

  • If the current element is equal to the previous one, skip it (handle duplicates).
  • Else, if the difference between the current and previous element is 1:
    • Increment cont_sub_sequence by 1.
  • Otherwise:
    • Update max_sequence as the maximum of max_sequence and cont_sub_sequence.
    • Reset cont_sub_sequence to 1.

3. After the loop, update max_sequence one final time as the maximum of max_sequence and cont_sub_sequence.

4. Return max_sequence.


class Solution:
    
    # arr[] : the input array
    
    #Function to return length of longest subsequence of consecutive integers.
    def longestConsecutive(self,arr):
        #code here
        arr.sort()
        max_sequence = 1
        cont_sub_sequence = 1
        for itr in range(1, len(arr)):
            if arr[itr] == arr[itr-1]:
                continue
            elif arr[itr] - arr[itr-1] == 1:
                cont_sub_sequence += 1
            else:
                if cont_sub_sequence > max_sequence:
                    max_sequence = cont_sub_sequence
                cont_sub_sequence = 1
        
        if cont_sub_sequence > max_sequence:
            max_sequence = cont_sub_sequence
        return max_sequence

POTD #7 – Count pairs with given sum | Geeks For Geeks

26 December 2024 at 18:50

Problem Statement

Geeks For Geeks – https://www.geeksforgeeks.org/problems/count-pairs-with-given-sum–150253/1

Given an arrayΒ arr[]Β and an integerΒ target.Β You have to find numbers of pairs in arrayΒ arr[]Β which sums up to givenΒ target.


Input: arr[] = [1, 5, 7, -1, 5], target = 6 
Output: 3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) and (1, 5). 

Input: arr[] = [1, 1, 1, 1], target = 2 
Output: 6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1).


Input: arr[] = [10, 12, 10, 15, -1], target = 125
Output: 0

My Approach

Today’s problem is similar to Two Sum problem, but with a counter.


class Solution:
    #Complete the below function
    def countPairs(self,arr, target):
        #Your code here
        hash_count = {}
        total_count = 0
        for num in arr:
            rem = target - num
            if hash_count.get(rem):
                total_count += hash_count.get(rem)
            hash_count[num] = hash_count.get(num, 0) + 1
        return total_count

❌
❌