❌

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 #13 – Subarrays with sum K | Geeks For Geeks

2 January 2025 at 17:11

Problem Statement

Geeks For Geeks: https://www.geeksforgeeks.org/problems/subarrays-with-sum-k/1

Given an unsorted array of integers, find the number of continuous subarrays having sum exactly equal to a given number k.


Input: arr = [10, 2, -2, -20, 10], k = -10
Output: 3
Explaination: Subarrays: arr[0...3], arr[1...4], arr[3...4] have sum exactly equal to -10.


Input: arr = [9, 4, 20, 3, 10, 5], k = 33
Output: 2
Explaination: Subarrays: arr[0...2], arr[2...4] have sum exactly equal to 33.


Input: arr = [1, 3, 5], k = 0
Output: 0
Explaination: No subarray with 0 sum.

My Approach 1 (Brute Force)

Initially i tried to solve it via bruteforce, but got timedout.


class Solution:
    def countSubarrays(self, arr, k):
        # code here
        continous_count = 0
        total_length = len(arr)
        for itr in range(total_length):
            _sum = arr[itr]
            # print("ITR", arr[itr])
            for jtr in range(itr+1, total_length):
                # print("JTR", arr[jtr])
                if _sum + arr[jtr] == k:
                    # print("SUM")
                    continous_count += 1
                _sum += arr[jtr]
        return continous_count

My Approach 2 (Optimal)

After some time, searched for an approach, then came across prefix-sum . So tried to apply the same,


class Solution:
    def countSubarrays(self, arr, k):
        n = len(arr)
        pre_sum_map = {}
        pre_sum = 0
        cnt = 0
    
        pre_sum_map[0] = 1
        for i in range(n):
            pre_sum += arr[i]
            remove = pre_sum - k
            cnt += pre_sum_map.get(remove, 0)
            pre_sum_map[pre_sum] = pre_sum_map.get(pre_sum, 0) + 1
    
        return cnt

Reference:

  1. https://takeuforward.org/arrays/count-subarray-sum-equals-k/
  2. https://www.youtube.com/watch?v=frf7qxiN2qU

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

POTD #6 – Two Sum – Pair with Given Sum | Geeks For Geeks

26 December 2024 at 06:05

Problem Statement

Geeks For Geeks : https://www.geeksforgeeks.org/problems/key-pair5616/1

Given an array arr[] of positive integers and another integer target. Determine if there exists two distinct indices such that the sum of there elements is equals to target.

Examples


Input: arr[] = [1, 4, 45, 6, 10, 8], target = 16
Output: true
Explanation: arr[3] + arr[4] = 6 + 10 = 16.


Input: arr[] = [1, 2, 4, 3, 6], target = 11
Output: false
Explanation: None of the pair makes a sum of 11.

My Approach

  • Iterate through the array
  • For each element, check whether the remaining (target – element) is also present in the array using the supportive hashmap.
  • If the remaining is also present then return True.
  • Else, save the element in the hashmap and go to the next element.

#User function Template for python3
class Solution:
	def twoSum(self, arr, target):
		# code here
		maps = {}
		for item in arr:
		    rem = target - item
		    if maps.get(rem):
		        return True
		    maps[item] = True
		return False
		

POTD #5 – Set Matrix Zeroes | Geeks For Geeks

25 December 2024 at 06:20

Problem Statement

Geeks For Geeks : https://www.geeksforgeeks.org/problems/set-matrix-zeroes/1

You are given a 2D matrix mat[][] of size nΓ—m.Β The task is to modify the matrix such that if mat[i][j] is 0, all the elements in theΒ i-th row and j-th column are set to 0 and do it in constant space complexity.


Input: mat[][] = [[1, -1, 1],
                [-1, 0, 1],
                [1, -1, 1]]
Output: [[1, 0, 1],
        [0, 0, 0],
        [1, 0, 1]]
Explanation: mat[1][1] = 0, so all elements in row 1 and column 1 are updated to zeroes.


Input: mat[][] = [[0, 1, 2, 0],
                [3, 4, 5, 2],
                [1, 3, 1, 5]]
Output: [[0, 0, 0, 0],
        [0, 4, 5, 0],
        [0, 3, 1, 0]]
Explanation: mat[0][0] and mat[0][3] are 0s, so all elements in row 0, column 0 and column 3 are updated to zeroes.

My Approach

  1. Iterate through the matrix and check whether mat[i][j] is zero. If its zero then row i and col j need to made as zeros.
  2. Collect them in a set
  3. Finally iterate through the set and update the matrix.

#User function Template for python3
class Solution:
    
    
    def setMatrixZeroes(self, mat):
        rows_to_zeros = set()
        cols_to_zeros = set()
        
        rows = len(mat)
        cols = len(mat[0])
        
        for i in range(rows):
            for j in range(cols):
                if mat[i][j] == 0:
                    rows_to_zeros.add(i)
                    cols_to_zeros.add(j)
        
        for row in rows_to_zeros:
            for itr in range(cols):
                mat[row][itr] = 0
        
        
        for col in cols_to_zeros:
            for itr in range(rows):
                mat[itr][col] = 0       
        
        return mat

POTD #3 Search in a row-wise sorted matrix | Geeks For Geeks

23 December 2024 at 10:25

Problem Statement

GFG Link – https://www.geeksforgeeks.org/problems/search-in-a-row-wise-sorted-matrix/1

Given a row-wise sorted 2D matrix mat[][] of size n x mΒ andan integer x, find whether element x is present in the matrix.
Note: In a row-wise sorted matrix, each row is sorted in itself, i.e. for any i, j within bounds, mat[i][j] <= mat[i][j+1].

Input: mat[][] = [[3, 4, 9],[2, 5, 6],[9, 25, 27]], x = 9
Output: true
Explanation: 9 is present in the matrix, so the output is true.

Input: mat[][] = [[19, 22, 27, 38, 55, 67]], x = 56
Output: false
Explanation: 56 is not present in the matrix, so the output is false.

My Approach:

Today’s problem is same as yesterday’s problem. But i got timed out. So instead of calculating the len(arr) each time (which is same always ) i just stored it in a variable and passed.

class Solution:
    def binary_search(self, arr, x, start, stop):
        if start > stop:
            return False
        mid = (start + stop) // 2
        if start == stop and arr[start] != x:
            return False
        if arr[mid] == x:
            result = self.binary_search(arr, x, 0, length)
        elif arr[mid] > x:
            return self.binary_search(arr, x, start, mid)
        else:
            return self.binary_search(arr, x, mid+1, stop)
    
    #Function to search a given number in row-column sorted matrix.
    def searchRowMatrix(self, mat, x): 
    	# code here 
    	length = len(mat[0]) - 1
    	for arr in mat:
            result = self.binary_search(arr, x, 0, length)
            if result:
                return True
        return False


Managing EKS Clusters Using AWS Lambda: A Step-by-Step Approach

By: Ragul.M
20 December 2024 at 12:20

Efficiently managing Amazon Elastic Kubernetes Service (EKS) clusters is critical for maintaining cost-effectiveness and performance. Automating the process of starting and stopping EKS clusters using AWS Lambda ensures optimal utilization and reduces manual intervention. Below is a structured approach to achieve this.

1. Define the Requirements

  • Identify the clusters that need automated start/stop operations.
  • Determine the dependencies among clusters, if any, to ensure smooth transitions.
  • Establish the scaling logic, such as leveraging tags to specify operational states (e.g., auto-start, auto-stop).

2. Prepare the Environment

  • AWS CLI Configuration: Ensure the AWS CLI is set up with appropriate credentials and access.
  • IAM Role for Lambda:
    • Create a role with permissions to manage EKS clusters (eks:DescribeCluster, eks:UpdateNodegroupConfig, etc.).
    • Include logging permissions for CloudWatch Logs to monitor the Lambda function execution.

3. Tag EKS Clusters

  • Use resource tagging to identify clusters for automation.
  • Example tags:
    • auto-start=true: Indicates clusters that should be started by the Lambda function.
    • dependency=<cluster-name>: Specifies any inter-cluster dependencies.

4. Design the Lambda Function

  • Trigger Setup:
    • Use CloudWatch Events or schedule triggers (e.g., daily or weekly) to invoke the function.
  • Environment Variables: Configure the function with environment variables for managing cluster names and dependency details.
  • Scaling Configuration: Ensure the function dynamically retrieves scaling logic via tags to handle operational states.

5. Define the Workflow

  • Fetch Cluster Information: Use AWS APIs to retrieve cluster details, including their tags and states.
  • Check Dependencies:
    • Identify dependent clusters and validate their status before initiating operations on others.
  • Start/Stop Clusters:
    • Update node group configurations or use cluster-level start/stop APIs where supported.
  • Implement Logging and Alerts: Capture the execution details and errors in CloudWatch Logs.

(If you want my code , just comment "ease-py-code" on my blog , will share you 🫢 )

6. Test and Validate

  • Dry Runs: Perform simulations to ensure the function executes as expected without making actual changes.
  • Dependency Scenarios: Test different scenarios involving dependencies to validate the logic.
  • Error Handling: Verify retries and exception handling for potential API failures.

7. Deploy and Monitor

  • Deploy the Function: Once validated, deploy the Lambda function in the desired region.
  • Set Up Monitoring:
    • Use CloudWatch Metrics to monitor function executions and errors.
    • Configure alarms for failure scenarios to take corrective actions.

By automating the start and stop operations for EKS clusters, organizations can significantly enhance resource management and optimize costs. This approach provides scalability and ensures that inter-cluster dependencies are handled efficiently.

Follow for more and happy learning :)

How to install AWS EKS Cluster

4 January 2024 at 01:43

Β 

step1: create EC2 instance

step2:
Create an IAM Role and attach it to EC2 instance 
IAM 
EC2 
VPC 
CloudFormation 
Administrative access

In the EC2 instance install kubectl and eksctl
step3: install kubectl
$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
$ chmod +x ./kubectl
$ sudo mv ./kubectl /usr/local/bin
$ kubectl version --client

step4: install eksctl
$ curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
$ sudo mv /tmp/eksctl /usr/local/bin
$ eksctl version

step5: install aws-iam-authenticator
$ curl -Lo aws-iam-authenticator https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/v0.6.14/aws-iam-authenticator_0.6.14_linux_amd64
$ chmod +x ./aws-iam-authenticator
$ mkdir -p $HOME/bin && cp ./aws-iam-authenticator $HOME/bin/aws-iam-authenticator && export PATH=$HOME/bin:$PATH
$ echo 'export PATH=$HOME/bin:$PATH' >> ~/.bashrc
step6:
create clusters and nodes
$ eksctl create cluster --name dhana-cluster --region ap-south-1 --node-type t2.small

step7:
Validate your cluster using by creating by checking nodes and by creating a pod
$ kubectl get nodes
$ kubectl run pod tomcat --image=tomcatΒ 
$ kubectl run pod nginx --image=nginx

To delete the cluster dhana-cluster
$ eksctl delete cluster dhana-cluster --region ap-south-1

❌
❌