Equal Beauty CodeChef SnackDown 2021 Round 1A Question The beauty of an (non-empty) array of integers is defined as the difference between its largest and smallest element. For example, the beauty of the array [2,3,4,4,6] is 6−2=4. An array A is said to be good if it is possible to partition the elements of A into two non-empty arrays B1 and B2 such that B1 and B2 have the same beauty. Each element of array A should be in exactly one array: either in B1 or in B2. For example, the array [6,2,4,4,4] is good because its elements can be partitioned into two arrays B1=[6,4,4] and B2=[2,4], where both B1 and B2 have the same beauty (6−4=4−2=2). You are given an array A of length N. In one move you can: Select an index i (1≤i≤N) and either increase Ai by 1 or decrease Ai by 1. Find the minimum number of moves required to make the array A good. Input Format The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follow. Each test
Word Search LeetCode Solution
Links
Question
Given an m x n
grid of characters board
and a string word
, return true
if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
andword
consists of only lowercase and uppercase English letters.
Explanation
This problem is based on a very popular concept that is backtracking. This concept is very important so you should understand the concept clearly and solve as many problems possible on this topic because this topic is among the favorite topics of interviewers in large tech companies like FAANG. Lets understand the problem statement first we are given a matrix of (m*n) and we need to check whether the given word exists in the matrix or not. We can move in four directions that is up, down, left, right. As the word can start in any position so we need to check for every position as any position can be the starting point. Now the logic is quite simple for every call we have the index variable which shows how much characters of words are already found in the current DFS call. If at any point we find a mismatch between the word[index] and board[x][y] then that branch becomes invalid and we need to change the branch which we considered. We use backtracking to ensure that each position or each block of matrix is visited once in a branch. That's it you just need to code it hope the explanation was clearly understood. I recommend to try it by yourself first then if you are stuck then you can check the solution below given in Java, C++, Python. Make sure you understand the explanation first then only you should go for the solution given below after having a try by yourself.
More information about LeetCode Daily Challenge
More Information About LeetCode Daily Challenge
LeetCode is a great coding platform which provides daily problems to solve and maintain a streak of coding. This platform helps in improvement of coding skills and attempting the daily challenge makes our practice of coding regular. With its bunch of questions available it is one of the best coding platforms where you can have self improvement. LeetCode also holds weekly and biweekly contests which is a great place to implement you knowledge and coding skills which you learnt through out the week by performing the daily challenge. It also provides badges if a coder solves all the daily problems of a month. For some lucky winners T-shirts are also given and that too for free. If you get the pro version you can get more from LeetCode like questions that are asked in interviews, detailed explanation of each chapter and each concept and much more. LeetCode challenges participants with a problem from our carefully curated collection of interview problems every 24 hours.
All users with all levels of coding background are welcome to join!
@PREMIUM USERS will have an extra carefully curated premium challenge weekly and earn extra LeetCoin rewards. The premium challenge will be available together with the first October challenge of the week and closed together with the November challenge of the week.
Starting from 2021, users who completed all Daily LeetCoding Challenge non-premium problems for the month (with or without using Time Travel Tickets) will win a badge to recognize their consistency! Your badges will be displayed on your profile page. Completing each non-premium daily challenge. (+10 LeetCoins)
Completing 25 to 30 non-premium daily challenges without using Time Travel Ticket will be eligible for an additional 25 LeetCoins. (Total = 275 to 325 LeetCoins)
Completing all 31 non-premium daily challenges without using Time Travel Ticket will be eligible for an additional 50 LeetCoins, plus a chance to win a secret prize ( Total = 385 LeetCoins + *Lucky Draw)!
Lucky Draw: Those who complete all 31 non-premium daily challenges will be automatically entered into a Lucky Draw, where LeetCode staff will randomly select 3 lucky participants to each receive one LeetCode Polo Shirt on top of their rewards! Do you have experience trying to keep a streak but failed because you missed one of the challenges?
Hoping you can travel back to the missed deadline to complete the challenge but that's not possible......or is it?
With the new Time Travel Ticket , it's possible! In order to time travel, you will need to redeem a Time Travel Ticket with your LeetCoins. You can redeem up to 3 tickets per month and the tickets are only usable through the end of the month in which they are redeemed but you can use the tickets to make up any invalid or late submission of the current year. To join, just start solving the daily problem on the calendar of the problem page. You can also find the daily problem listed on the top of the problem page. No registration is required. The daily problem will be updated on every 12 a.m. Coordinated Universal Time (UTC) and you will have 24 hours to solve that challenge. Thar's all you needed to know about Daily LeetCode Challenge.
Program Code
Java
class Solution {
int row;
int col;
public boolean exist(char[][] board, String word) {
row = board.length;
col = board[0].length;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(crosswordUtil(board, i, j, 0, word)) {
return true;
}
}
}
return false;
}
private boolean crosswordUtil(char[][] board, int i, int j, int startIndex, String word) {
if(startIndex == word.length())
return true;
if(i > row -1 || i < 0 || j < 0 || j > col - 1|| board[i][j] != word.charAt(startIndex))
return false;
board[i][j] = '$';
boolean exists = crosswordUtil(board, i-1, j, startIndex+1, word) ||
crosswordUtil(board, i+1, j, startIndex+1, word) ||
crosswordUtil(board, i, j-1, startIndex+1, word) ||
crosswordUtil(board, i, j+1, startIndex+1, word);
board[i][j] = word.charAt(startIndex);
return exists;
}
}
C++
class Solution {
public:
bool dfs(vector<vector<char>>& board,string word,int x,int y,int index)
{
if (index==word.length()) return true;
if (x>=board.size() || x<0 || y<0 || y>=board[0].size() || board[x][y]=='#' || board[x][y]!=word[index]) return false;
char c= board[x][y];
board[x][y]='#';
bool a= (dfs(board,word,x+1,y,index+1) || dfs(board,word,x-1,y,index+1) || dfs(board,word,x,y+1,index+1) || dfs(board,word,x,y-1,index+1));
board[x][y]=c;
return a;
}
bool exist(vector<vector<char>>& board, string word) {
for (int i=0;i<board.size();i++)
{
for (int j=0;j<board[0].size();j++)
{
if (board[i][j]==word[0])
{
if (dfs(board,word,i,j,0)) return true;
}
}
}
return false;
}
};
Python
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfssearch(board, r, c, word_i, visited):
if word_i == len(word) - 1:
return True
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
visited.add((r, c))
for d in directions:
newr, newc = r + d[0], c + d[1]
if 0 <= newr < len(board) and 0 <= newc < len(board[0]) and \
(newr, newc) not in visited and board[newr][newc] == word[word_i + 1]:
if dfssearch(board, newr, newc, word_i + 1, visited):
return True
visited.remove((r, c))
return False
visited = set()
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == word[0] and dfssearch(board, r, c, 0, visited):
return True
return False
Comments
Post a Comment