Biweekly Contest 80 LeetCode Solution

Problem 1 – Strong Password Checker II Leetcode Solution

A password is said to be strong if it satisfies all the following criteria:

  • It has at least 8 characters.
  • It contains at least one lowercase letter.
  • It contains at least one uppercase letter.
  • It contains at least one digit.
  • It contains at least one special character. The special characters are the characters in the following string: "[email protected]#$%^&*()-+".
  • It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not).

Given a string password, return true if it is a strong password. Otherwise, return false.

Example 1:

Input: password = "IloveLe3tcode!"
Output: true
Explanation: The password meets all the requirements. Therefore, we return true.

Example 2:

Input: password = "Me+You--IsMyDream"
Output: false
Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.

Example 3:

Input: password = "1aB!"
Output: false
Explanation: The password does not meet the length requirement. Therefore, we return false.

Constraints:

  • 1 <= password.length <= 100
  • password consists of letters, digits, and special characters: "[email protected]#$%^&*()-+".

Strong Password Checker II Leetcode Solution in C++

class Solution {
public:
    bool strongPasswordCheckerII(string p) {
        if(size(p) < 8) return false;
        bool low = false , upper = false ,digit = false ,special = false;
        for(auto c : p){
            if(c>='a' and c<='z') low = true;
            else if(c>='A' and c <='Z') upper = true;
            else if(isdigit(c)) digit = true;
            else special = true;
        }
        //Check the 6th condition
        for(int i=0;i+1<size(p);i++) if(p[i] == p[i+1]) return false;
        if(low and upper and digit and special) return true;
        return false;
    }
};

Strong Password Checker II Leetcode Solution in Java

class Solution {
    //lc-> LowerCase;
	//uc-> UpperCase;
	//d-> Digit;
	//sc-> Special Case;
	
    public boolean strongPasswordCheckerII(String password) {
        if(password.length()<8)return false;
        boolean res=false;
        
        boolean lc=false;
        boolean uc=false;
        boolean d=false;
        boolean sc=false;
        
        for(int i=0;i<password.length();i++){
            char ch=password.charAt(i);
            if(i>0 && ch==password.charAt(i-1))return false;
            
            if(ch>='0' && ch<='9')d=true;
            if(ch>='a' && ch<='z')lc=true;
            if(ch>='A' && ch<='Z')uc=true;
            if(ch=='!'||ch=='@'||ch=='#'||ch=='$'||ch=='%'||ch=='^'||ch=='&'||ch=='*'||ch=='('||ch==')'||ch=='-'||ch=='+')sc=true;
            
        }
        
        res=lc&uc&d&sc;
        return res;
    }
}

Strong Password Checker II Leetcode Solution in Python

class Solution:
    def strongPasswordCheckerII(self, password: str) -> bool:
        oneUpper, oneLower, oneDigit, oneSpl = False, False, False, False

        if len(password) < 8:
            return False
        for idx, p in enumerate(password):
            if p.isupper():
                oneUpper = True
            if p.islower():
                oneLower = True
            if p.isdigit():
                oneDigit = True
            if p in ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+']:
                oneSpl = True
            if idx < len(password) - 1:
                if password[idx] == password[idx + 1]:
                    return False

        return oneUpper and oneSpl and oneDigit and oneLower

Strong Password Checker II Leetcode Solution in JavaScript

const ord = (c) => c.charCodeAt();
const isLowerCase = (c) => { let x = ord(c); return x >= 97 && x <= 122; };
const isUpperCase = (c) => { let x = ord(c); return x >= 65 && x <= 90; };
const isDigit = (c) => '0123456789'.indexOf(c) != -1;
const isSpecial = (c) => '[email protected]#$%^&*()-+'.indexOf(c) != -1;

const strongPasswordCheckerII = (s) => {
    let n = s.length, hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false, adjSame = false;
    if (n < 8) return false;
    for (let i = 0; i < n; i++) {
        if (isLowerCase(s[i])) hasLower = true;
        if (isUpperCase(s[i])) hasUpper = true;
        if (isDigit(s[i])) hasDigit = true;
        if (isSpecial(s[i])) hasSpecial = true;
        if (i + 1 < n && s[i] == s[i + 1]) adjSame = true;
    }
    return hasLower && hasUpper && hasDigit && hasSpecial && !adjSame;
};

Problem 2 – Successful Pairs of Spells and Potions Leetcode Solution

You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.

You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.

Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.

Example 1:

Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.

Example 2:

Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. 
- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. 
Thus, [2,0,2] is returned.

Constraints:

  • n == spells.length
  • m == potions.length
  • 1 <= n, m <= 105
  • 1 <= spells[i], potions[i] <= 105
  • 1 <= success <= 1010

Successful Pairs of Spells and Potions Leetcode Solution in C++

    vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
        sort(potions.begin(), potions.end());
        vector<int> res;
        for (int a: spells) {
            long need = (success + a - 1) / a;
            auto it = lower_bound(potions.begin(), potions.end(), need);
            res.push_back(potions.end() - it);
        }
        return res;
    }

Successful Pairs of Spells and Potions Leetcode Solution in Python

    def successfulPairs(self, spells, potions, success):
        potions.sort()
        return [len(potions) - bisect_left(potions, (success + a - 1) // a) for a in spells]

Successful Pairs of Spells and Potions Leetcode Solution in Java

    public int[] successfulPairs(int[] spells, int[] potions, long success) {
        int[] spells0 = spells.clone();
        Arrays.sort(potions);
        Arrays.sort(spells);
        HashMap<Integer, Integer> count = new HashMap<>();
        int n = spells.length, m = potions.length, j = m - 1, res[] = new int[n];
        for (int i = 0; i < n; ++i) {
            while (j >= 0 && 1L * spells[i] * potions[j] >= success)
                j--;
            count.put(spells[i], m - j - 1);
        }
        for (int i = 0; i < n; ++i) {
            res[i] = count.get(spells0[i]);
        }
        return res;
    }

Successful Pairs of Spells and Potions Leetcode Solution in Python 3

    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
        potions.sort()
        pairs = []
        for s in spells:
            factor = (success + s - 1) // s
            pairs.append(len(potions) - bisect.bisect_left(potions, factor))
        return pairs

Problem 3 – Match Substring After Replacement Leetcode Solution

You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may replace any number of oldi characters of sub with newi. Each character in sub cannot be replaced more than once.

Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false.

substring is a contiguous non-empty sequence of characters within a string.

Example 1:

Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]]
Output: true
Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'.
Now sub = "l3e7" is a substring of s, so we return true.

Example 2:

Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]]
Output: false
Explanation: The string "f00l" is not a substring of s and no replacements can be made.
Note that we cannot replace '0' with 'o'.

Example 3:

Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]]
Output: true
Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.
Now sub = "l33tb" is a substring of s, so we return true.

Constraints:

  • 1 <= sub.length <= s.length <= 5000
  • 0 <= mappings.length <= 1000
  • mappings[i].length == 2
  • oldi != newi
  • s and sub consist of uppercase and lowercase English letters and digits.
  • oldi and newi are either uppercase or lowercase English letters or digits.

Match Substring After Replacement Leetcode Solution in C++

class Solution {
public:
    unordered_map<char, unordered_map<char, char>> isMappingExist;
    
    bool check(string& s, int pos, string& sub) {
        // Return if the substring cannot exist
        if (pos + sub.size() > s.size()) {
            return false;
        }
        
        int index = 0;
        for (int i = pos; i < pos + sub.size(); i++) {
            if (sub[index] == s[i] || isMappingExist[sub[index]][s[i]]) {
                index++;
            } else {
                return false;
            }
        }
        
        return true;
    }
    
    bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) {
        for (vector<char> mapping : mappings) {
            isMappingExist[mapping[0]][mapping[1]] = 1;
        }
        
        for (int i = 0; i < s.size(); i++) {
            if (check(s, i, sub)) {
                return true;
            }
        }
        
        return false;
    }
};

Match Substring After Replacement Leetcode Solution in Python

class Solution:
    def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:
        regexp = []
        m = defaultdict(lambda: set())
        for f, t in mappings:
            m[f].add(t)
        def search(i, j):
            len_s = len(s)
            len_sub = len(sub)
            while j < len(sub):
                lenlefts = len_s - i
                lenleftsub = len_sub - j
                if lenlefts < lenleftsub:
                    return False
                elif (s[i] == sub[j]) or (s[i] in m[sub[j]]):
                    i+=1
                    j+=1
                    continue
                else:
                    return False
            return True
        for i in range(len(s)):
            if search(i, 0):
                return True
        return False

Match Substring After Replacement Leetcode Solution in Java

class Solution {
    public boolean matchReplacement(String s, String sub, char[][] mappings) {
        HashMap<Character, HashSet<Character>> m = new HashMap<Character, HashSet<Character>>();
        for(char[] carr: mappings) {
            if (!m.containsKey(carr[0])){
                m.put(carr[0], new HashSet<Character>());
            }
            m.get(carr[0]).add(carr[1]);
        }
        int len_s = s.length();
        int len_sub = sub.length();
        for (int pos = 0; pos < s.length(); pos++ ){
            int i = pos;
            int j = 0;
            boolean cont = false; 
            while (j < sub.length()) {
                int lenlefts = len_s - i;
                int lenleftsub = len_sub - j;
                if (lenlefts < lenleftsub) {
                    cont = true;
                    break;
                } else if ((s.charAt(i) == sub.charAt(j)) || (m.containsKey(sub.charAt(j)) && m.get(sub.charAt(j)).contains( s.charAt(i)))) {
                    i+=1;
                    j+=1;
                    continue;
                } else {
                    cont = true;
                    break;
                }
            }
            if (cont) {
                continue;
            }
            return true;

        }
        return false;
    }
}

Problem 4 – Count Subarrays With Score Less Than K Leetcode Solution

The score of an array is defined as the product of its sum and its length.

  • For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.

Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.

subarray is a contiguous sequence of elements within an array.

Example 1:

Input: nums = [2,1,4,3,5], k = 10
Output: 6
Explanation:
The 6 subarrays having scores less than 10 are:
- [2] with score 2 * 1 = 2.
- [1] with score 1 * 1 = 1.
- [4] with score 4 * 1 = 4.
- [3] with score 3 * 1 = 3. 
- [5] with score 5 * 1 = 5.
- [2,1] with score (2 + 1) * 2 = 6.
Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.

Example 2:

Input: nums = [1,1,1], k = 5
Output: 5
Explanation:
Every subarray except [1,1,1] has a score less than 5.
[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.
Thus, there are 5 subarrays having scores less than 5.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= k <= 1015

Count Subarrays With Score Less Than K Leetcode Solution in Java

    public long countSubarrays(int[] A, long k) {
        long res = 0, cur = 0;
        for (int j = 0, i = 0; j < A.length; ++j) {
            cur += A[j];
            while (cur * (j - i + 1) >= k)
                cur -= A[i++];
            res += j - i + 1;
        }
        return res;
    }

Count Subarrays With Score Less Than K Leetcode Solution in C++

    long long countSubarrays(vector<int>& A, long long k) {
        long long res = 0, cur = 0;
        for (int j = 0, i = 0; j < A.size(); ++j) {
            cur += A[j];
            while (cur * (j - i + 1) >= k)
                cur -= A[i++];
            res += j - i + 1;
        }
        return res;
    }

Count Subarrays With Score Less Than K Leetcode Solution in Python

    def countSubarrays(self, A, k):
        res = cur = i = 0
        for j in range(len(A)):
            cur += A[j]
            while cur * (j - i + 1) >= k:
                cur -= A[i]
                i += 1
            res += j - i + 1
        return res

Count Subarrays With Score Less Than K Leetcode Solution in Python 3

class Solution:
    def countSubarrays(self, nums: List[int], k: int) -> int:
        sum, res, j = 0, 0, 0
        for i, n in enumerate(nums):
            sum += n
            while sum * (i - j + 1) >= k:
                sum -= nums[j]
                j += 1
            res += i - j + 1
        return res
Biweekly Contest 80 LeetCode Solution Review:

In our experience, we suggest you solve this Biweekly Contest 80 LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Biweekly Contest 80 LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Biweekly Contest 80 LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.