Skip to main content

Equal Beauty CodeChef SnackDown 2021 Round 1A

 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

Split Linked List in Parts LeetCode Solution

 Split Linked List in Parts LeetCode Solution

Question

Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.

The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

Return an array of the k parts.

Example 1:

Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but its string representation as a ListNode is [].

Example 2:

Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
Output: [[1,2,3,4],[5,6,7],[8,9,10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

Constraints:

  • The number of nodes in the list is in the range [0, 1000].
  • 0 <= Node.val <= 1000
  • 1 <= k <= 50

Explanation

The question is of medium category of LeetCode. To solve this problem you need a clear idea about linked list and some knowledge regarding splitting of linked list.Firstly, we need to get length of the linked list start with head node, let say listSize. We need to split into k parts, where the length of each part should be as equal as possible: Each part have the size, partSize = listSize / k. When dividing into k parts, there may have some remain elements, remainSize = listSize % k. We need to prioritize filling those remaining elements into earlier parts since the problem said: parts occurring earlier should always have a size greater than or equal to parts occurring later. The time complexity of this code is O(N) and the space complexity of this code is O(1). That's all now code it. Hope you understood the explanation. I recommend to try the problem by yourself first then you can have a look at the solution given below in Java, C++, Python. 

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 
{
    public ListNode[] splitListToParts(ListNode head, int k) 
    {
        ListNode temp = head;
        
        int size = 0;
        
        while(temp != null)
        {
            size++;
            
            temp = temp.next;
        }
        
        ListNode ans[] = new ListNode[k];
        
        int s[] = new int[k];
        
        int c = 0;
        
        while(size-- > 0)
        {
            s[c % k]++;
            
            c++;
        }
        
        temp = head;
        
        int idx = 0;
    
        for(int num : s)
        {
            ListNode hh = null;
            
            ListNode tt = null;
            
            while(num-- > 0)
            {
                if(tt == null)
                {
                    hh = new ListNode(temp.val);
                    
                    tt = hh;
                }
                
                else
                {
                    tt.next = new ListNode(temp.val);
                    
                    tt = tt.next;
                }
                
                temp = temp.next;
            }
            
            ans[idx++] = hh;
        }
        
        return ans;
    }
}

C++

class Solution {
public:
	vector<ListNode*> splitListToParts(ListNode* head, int k) {
		int ListLen = 0, eachLen = 0, remain = 0, size = 0, len = 0;
		ListNode *cur = NULL, *prev = NULL, *newHead = NULL;
		/* Init answer vector<ListNode*> to k NULL lists. */
		vector<ListNode*> ans = vector<ListNode*>(k, NULL);

		/* Get input list length. */
		cur = head;
		while(cur != NULL) {
			ListLen++;
			cur = cur->next;
		}

		eachLen = ListLen / k;
		remain = (ListLen % k);

		cur = head;
		newHead = head;

		/* Assign the remain to the first few lists */
		len = eachLen + (remain > 0 ? 1 : 0);
		remain--;

		while(cur != NULL) {
			if (--len == 0) {
				prev = cur;
				cur = cur->next;
				prev->next = NULL;
				ans[size++] = newHead;
				newHead = cur;

				len = eachLen + (remain > 0 ? 1 : 0);
				remain--;

			} else {
				cur = cur->next;
			}
		}

		return ans;

	}
};

Python

class Solution:
    def splitListToParts(self, root, k):
        cur = root
        N = 0
        while cur:
            cur = cur.next
            N += 1
        d, r = divmod(N, k)

        ans = []
        cur = root
        for i in range(k):
            head = cur
            for j in range(d + (i < r) - 1):
                if cur: cur = cur.next
            if cur:
                cur.next, cur = None, cur.next
            ans.append(head)
        return ans

Comments

Popular posts from this blog

Snake Procession CodeChef SnackDown 2021 Beginner Practice Contest

 Snake Procession CodeChef SnackDown 2021 Beginner Practice Contest Question: The annual snake festival is upon us, and all the snakes of the kingdom have gathered to participate in the procession. Chef has been tasked with reporting on the procession, and for this he decides to first keep track of all the snakes. When he sees a snake first, it'll be its Head, and hence he will mark a 'H'. The snakes are long, and when he sees the snake finally slither away, he'll mark a 'T' to denote its tail. In the time in between, when the snake is moving past him, or the time between one snake and the next snake, he marks with '.'s. Because the snakes come in a procession, and one by one, a valid report would be something like "..H..T…HTH….T.", or "…", or "HT", whereas "T…H..H.T", "H..T..H", "H..H..T..T" would be invalid reports (See explanations at the bottom). Formally, a snake is represented by a 'H&

Qualifying to Pre-Elimination CodeChef SnackDown 2021 Beginner Practice Contest

 Qualifying to Pre-Elimination  CodeChef SnackDown 2021 Beginner Practice Contest Question: Snackdown 2019 is coming! There are two rounds (round A and round B) after the qualification round. From both of them, teams can qualify to the pre-elimination round. According to the rules, in each of these two rounds, teams are sorted in descending order by their score and each team with a score greater or equal to the score of the team at the  K = 1500 K = 1500 -th place advances to the pre-elimination round (this means it is possible to have more than  K K  qualified teams from each round in the case of one or more ties after the  K K -th place). Today, the organizers ask you to count the number of teams which would qualify for the pre-elimination round from round A for a given value of  K K  (possibly different from  1500 1500 ). They provided the scores of all teams to you; you should ensure that all teams scoring at least as many points as the  K K -th team qualify. Input: The first line

Chef and Typing CodeChef SnackDown 2021 Beginner Practice Contest

 Chef and Typing CodeChef SnackDown 2021 Beginner Practice Contest Question: Chef is practising his typing skills since his current typing speed is very low. He uses a training application that displays some words one by one for Chef to type. When typing a word, Chef takes 0.2 seconds to type the first character; for each other character of this word, he takes 0.2 seconds to type this character if it is written with a different hand than the previous character, or 0.4 seconds if it is written with the same hand. The time taken to type a word is the sum of times taken to type all of its characters. However, if a word has already appeared during practice, Chef can type it in half the time it took him to type this word for the first time. Currently, Chef is practising in easy mode, which only uses words that consists of characters 'd', 'f', 'j' and 'k'. The characters 'd' and 'f' are written using the left hand, while the characters 'j&#

Kitchen Timetable CodeChef SnackDown 2021 Beginner Practice Contest Solution

 Kitchen Timetable CodeChef SnackDown 2021 Beginner Practice Contest Solution Question: There are  N  students living in the dormitory of Berland State University. Each of them sometimes wants to use the kitchen, so the head of the dormitory came up with a timetable for kitchen's usage in order to avoid the conflicts: The first student starts to use the kitchen at the time  0  and should finish the cooking not later than at the time  A 1 . The second student starts to use the kitchen at the time  A 1  and should finish the cooking not later than at the time  A 2 . And so on. The  N -th student starts to use the kitchen at the time  A N-1  and should finish the cooking not later than at the time  A N The holidays in Berland are approaching, so today each of these  N  students wants to cook some pancakes. The  i -th student needs  B i  units of time to cook. The students have understood that probably not all of them will be able to cook everything they want. How many students will be

Chef and Operations CodeChef SnackDown 2021 Beginner Practice Contest

Chef and Operations CodeChef SnackDown 2021 Beginner Practice Contest Question: Chef has two sequences  A A  and  B B , each with length  N N . He can apply the following magic operation an arbitrary number of times (including zero): choose an index  i i  ( 1 ≤ i ≤ N − 2 1 ≤ i ≤ N − 2 ) and add  1 1  to  A i A i ,  2 2  to  A i + 1 A i + 1  and  3 3  to  A i + 2 A i + 2 , i.e. change  A i A i  to  A i + 1 A i + 1 ,  A i + 1 A i + 1  to  A i + 1 + 2 A i + 1 + 2  and  A i + 2 A i + 2  to  A i + 2 + 3 A i + 2 + 3 . Chef asks you to tell him if it is possible to obtain sequence  B B  from sequence  A A  this way. Help him! Input: The first line of the input contains a single integer  T  denoting the number of test cases. The description of  T  test cases follows. The first line of each test case contains a single integer  N . The second line contains  N  space-separated integers  A 1 , A 2 , … , A N . The third line contains  N  space-separated integers  B 1 , B 2 , … , B B 1 , B 2 , … , B

Round Robin Ranks CodeChef SnackDown 2021 Round 1A

 Round Robin Ranks CodeChef SnackDown 2021 Round 1A Question A round-robin tournament is being held in Chefland among N teams numbered 1,2,...,N. Every team play with all other teams exactly once. All games have only two possible results - win or loss. A win yields 2 points to the winning team while a loss yields no points. What is the maximum number of points a team finishing at the Kth position can score? Note: If two teams have the same points then the team with the higher team number achieves the better rank. Input Format First line will contain T, number of testcases. Then the testcases follow. Each testcase contains a single line of input, two space-separated integers N,K. Output Format For each testcase, output in a single line an integer - the maximum points the team ranked K in the round-robin tournament can score. Constraints 1≤T≤10^5 1≤K≤N≤10^9 Sample Input 1  3 3 3 4 1 7 4 Sample Output 1  2 6 8 Explanation Test Case 1: There are 3 teams in the tournament. The maximum score

Temple Land CodeChef SnacKDown 2021 Beginner Practice Contest

 Temple Land CodeChef SnacKDown 2021 Beginner Practice Contest Question: The snakes want to build a temple for Lord Cobra. There are multiple strips of land that they are looking at, but not all of them are suitable. They need the strip of land to resemble a coiled Cobra. You need to find out which strips do so. Formally, every strip of land, has a length. Suppose the length of the i-th strip is is  N i , then there will be  N i  integers,  H i1 , H i2 , .. H iN i , which represent the heights of the ground at various parts of the strip, in sequential order. That is, the strip has been divided into  N i  parts and the height of each part is given. This strip is valid, if and only if all these conditions are satisfied: There should be an unique 'centre' part. This is where the actual temple will be built. By centre, we mean that there should be an equal number of parts to the left of this part, and to the right of this part. H i1  = 1 The heights keep increasing by exactly 1, as

Delete Two Elements Educational Codeforces Round 115 Solution

 Delete Two Elements Educational Codeforces Round 115 Solution Introduction Educational Codeforces rounds are organized by Codeforces for the Division 2 Coders. Similarly Educational Codeforces Round was held on     Sunday, October 10, 2021 at 14:35 UTC+5.5   Series of Educational Rounds continue to be held as Harbour Space University initiative. This round will be rated for coders with rating upto 2100. It will be held on extended ICPC rules. The penalty for each incorrect submission until the full correct solution is 10 minutes. After the end of the contest you will have 12 hours to hack any solution. You will be given 7 problems and two hours to solve them.  The contest was a success and lots of submissions were made by the hard striving coders. Problem A that is the Computer Game was very easy and had the maximum number of successful submission. Problem B was a not easy but not difficult also it was fit for an average coder to solve. Problem C although was quite confusing at the st

Dance Moves CodeChef SnackDown 2021 Round 1A Solution

 Dance Moves CodeChef SnackDown 2021 Round 1A Solution Question This year Chef is participating in a Dancing competition. The dance performance will be done on a linear stage marked with integral positions. Initially, Chef is present at position X and Chef's dance partner is at position Y. Chef can perform two kinds of dance moves. If Chef is currently at position k, Chef can: Moonwalk to position k+2, or Slide to position k−1 Chef wants to find the minimum number of moves required to reach his partner. Can you help him find this number? Input Format First line will contain a single integer T, the number of testcases. Then the description of T testcases follows. Each testcase contains a single line with two space-separated integers X,Y, representing the initial positions of Chef and his dance partner, respectively. Output Format For each testcase, print in a separate line, a single integer, the minimum number of moves required by Chef to reach his dance partner. Constraints 1≤T≤10^

Unique Email Addresses LeetCode Solution

Unique Email Addresses LeetCode Solution   Question Every  valid email  consists of a  local name  and a  domain name , separated by the  '@'  sign. Besides lowercase letters, the email may contain one or more  '.'  or  '+' . For example, in  "alice@leetcode.com" ,  "alice"  is the  local name , and  "leetcode.com"  is the  domain name . If you add periods  '.'  between some characters in the  local name  part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule  does not apply  to  domain names . For example,  "alice.z@leetcode.com"  and  "alicez@leetcode.com"  forward to the same email address. If you add a plus  '+'  in the  local name , everything after the first plus sign  will be ignored . This allows certain emails to be filtered. Note that this rule  does not apply  to  domain names . For example,  "m.y+name@ema