Posts

Showing posts from April, 2023

Swap Lex Order - CodeSignal

Given a string str and an array of pairs that indicate which indices in the string can be swapped, the function solution(str, pairs) returns the lexicographically largest string that results from doing the allowed swaps. Indices can be swapped any number of times. Example: For str = "abdc" and pairs = [[1, 4], [3, 4]] , the output should be solution(str, pairs) = "dbca" . By swapping the given indices, you get the strings: "cbda", "cbad", "dbac", "dbca". The lexicographically largest string in this list is "dbca". Input/Output: Execution time limit: 4 seconds (py3) str : a string consisting only of lowercase English letters with guaranteed constraints of 1 ≤ str.length ≤ 104 . pairs : an array containing pairs of indices that can be swapped in str (1-based). This means that for each pairs[i] , you can swap elements in str that have the indices pairs[i][0] and pairs[i][1] with guaranteed constraints of 0 ≤ pair

Maximum Sum Rectangle in a 2D array

Image
           Sample Test case:                                   Answer                                                                  Naive Approach:           The naive approach to find the maximum sum rectangle in a 2D array involves generating all possible submatrices and calculating their sum, and then selecting the maximum sum submatrix among them.  Each submatrix is generated by selecting its top-left corner and bottom-right corner.            Although this approach is simple to implement, it is not efficient for large inputs since its time complexity is very high. Therefore, more efficient algorithms like Kadane's algorithm for 2D arrays are used to solve this problem. Code: (C++)           #include < iostream > #include < bits/stdc++.h > using namespace std ; int maxSumRectangle ( vector < vector < int >> & arr , int n , int m ) { int nrow = arr . size (); int ncol = arr [ 0 ] . size (); int maxSum = INT_MIN ; fo