Zebra Crossing CodeChef Solution

Problem -Zebra Crossing CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Zebra Crossing CodeChef Solution in C++17

#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define endl "\n"
void solve(){
    int n,k;
    cin>>n>>k;
    string s;
    cin>>s;
    int arr[n];
    
    int val;
    int cnt=0;
    for(int i=0;i<n;i++){
        arr[i]=s[i]-'0';
        if(i==0){
           val=arr[i];
        }
        else if(arr[i]!=val){
            cnt++;
            val=arr[i];
        }
    }
    // cout<<cnt<<endl;
    if(cnt<k){
        cout<<-1<<endl;
    }
    else if(k%2==1){
        for(int i=n-1;i>0;i--){
            if(arr[i]!=arr[0]){
                cout<<i+1<<endl;
                break;
            }
        }

    }
    else{
        for(int i=n-1;i>0;i--){
            if(arr[i]==arr[0]){
                cout<<i+1<<endl;
                break;
            }
        }
    }
}
signed main()
{
    
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int T;
    cin>>T;
    while(T--){
        solve();
    }
    return 0;
}

Zebra Crossing CodeChef Solution in C++14

#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define endl "\n"
void solve(){
    int n,k;
    cin>>n>>k;
    string s;
    cin>>s;
    int arr[n];
    
    int val;
    int cnt=0;
    for(int i=0;i<n;i++){
        arr[i]=s[i]-'0';
        if(i==0){
           val=arr[i];
        }
        else if(arr[i]!=val){
            cnt++;
            val=arr[i];
        }
    }
    // cout<<cnt<<endl;
    if(cnt<k){
        cout<<-1<<endl;
    }
    else if(k%2==1){
        for(int i=n-1;i>0;i--){
            if(arr[i]!=arr[0]){
                cout<<i+1<<endl;
                break;
            }
        }

    }
    else{
        for(int i=n-1;i>0;i--){
            if(arr[i]==arr[0]){
                cout<<i+1<<endl;
                break;
            }
        }
    }
}
signed main()
{
    
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int T;
    cin>>T;
    while(T--){
        solve();
    }
    return 0;
}

Zebra Crossing CodeChef Solution in PYTH 3

def soln(n, k, s):
    cond = ""
    inds = []
    i = 0
    while i < n:
        cur = s[i]
        cond += s[i]
        while i < n and s[i] == cur:
            i += 1
        inds.append(i)
    if k >= len(cond):
        return -1
    if cond[0] == cond[-1]:
        if k&1:
            return inds[-2]
        else:
            return inds[-1]
    else:
        if k&1:
            return inds[-1]
        else:
            return inds[-2]

for _ in range(int(input())):
    n, k = map(int, input().split())
    s = input()
    print(soln(n, k, s))

Zebra Crossing CodeChef Solution in C

#include<stdio.h>
#include<malloc.h>

struct arr{
int N;
int K;
char *s;
};

int main(){
int i,n,temp,boo,j;
struct arr *A;
scanf("%d",&n);
A=(struct arr*)malloc(n*sizeof(struct arr));
for(i=0;i<n;++i){
    scanf("%d %d",&A[i].N,&A[i].K);
    A[i].s=(char*)malloc((A[i].N+1)*sizeof(char));
    scanf("%s",A[i].s);
}
for(i=0;i<n;++i){
    if(A[i].s[0]=='0'){
        if(A[i].K%2==0){
            temp=0;
            boo=0;
            for(j=A[i].N-1;j>=1;--j){
                if(boo==0&&A[i].s[j]=='0'){
                    temp=temp+1;
                    boo=1;
                }
                if(boo==1&&A[i].s[j]=='1'){
                    temp=temp+1;
                    boo=0;
                }
            }
            if(temp>=A[i].K){
                for(j=A[i].N-1;j>=1;--j){
                    if(A[i].s[j]=='0'){
                        printf("%d\n",j+1);
                        break;
                    }
                }
            }
            else printf("-1\n");
        }
         if(A[i].K%2!=0){
            temp=0;
            boo=0;
            for(j=A[i].N-1;j>=1;--j){
                if(boo==0&&A[i].s[j]=='1'){
                    temp=temp+1;
                    boo=1;
                }
                if(boo==1&&A[i].s[j]=='0'){
                    temp=temp+1;
                    boo=0;
                }
            }
            if(temp>=A[i].K){
                for(j=A[i].N-1;j>=1;--j){
                    if(A[i].s[j]=='1'){
                        printf("%d\n",j+1);
                        break;
                    }
                }
            }
            else printf("-1\n");
        }
    }
    if(A[i].s[0]=='1'){
        if(A[i].K%2==0){
            temp=0;
            boo=0;
            for(j=A[i].N-1;j>=1;--j){
                if(boo==0&&A[i].s[j]=='1'){
                    temp=temp+1;
                    boo=1;
                }
                if(boo==1&&A[i].s[j]=='0'){
                    temp=temp+1;
                    boo=0;
                }
            }
            if(temp>=A[i].K){
                for(j=A[i].N-1;j>=1;--j){
                    if(A[i].s[j]=='1'){
                        printf("%d\n",j+1);
                        break;
                    }
                }
            }
            else printf("-1\n");
        }
         if(A[i].K%2!=0){
            temp=0;
            boo=0;
            for(j=A[i].N-1;j>=1;--j){
                if(boo==0&&A[i].s[j]=='0'){
                    temp=temp+1;
                    boo=1;
                }
                if(boo==1&&A[i].s[j]=='1'){
                    temp=temp+1;
                    boo=0;
                }
            }
            if(temp>=A[i].K){
                for(j=A[i].N-1;j>=1;--j){
                    if(A[i].s[j]=='0'){
                        printf("%d\n",j+1);
                        break;
                    }
                }
            }
            else printf("-1\n");
        }
    }
}
return 0;
}

Zebra Crossing CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner sc = new Scanner(System.in);
		int T= sc.nextInt();
		while(T-->0){
		    int n = sc.nextInt();
		    int k = sc.nextInt();
		    String s = sc.next();
		    int lastIndex= -1;
		    int lastIndexOfone =-1;
		    int c1=0;
		    int c2=0;
		    for(int i=0;i<n ;i++){
		        if(s.charAt(i)=='1'){
		            lastIndexOfone =i;
		            c1++;
		        }else{
		            lastIndex=i;
		            c2++;
		        }
		        
		    }
		  //  int res = Math.max(c1,c2)- Math.abs(c1-c2);
		  //  if(((res*2)-1)<k){
		  //      System.out.println("-1");
		  //  }
		  char prev= s.charAt(0);
		  int K =k;
		  for(int i = 1 ; i < n && K > 0; i++){
                    if(s.charAt(i) != prev){
                        --K;
                        prev = s.charAt(i);
                    }
                }
                if(K > 0) {
                    System.out.println("-1");
                continue;
                }else{
		        if(s.charAt(0)=='1'){
		            if(k%2==0){
		                System.out.println(lastIndexOfone+1);
		            }else{
		                System.out.println(lastIndex+1);
		            }
		        }else{
		            if(k%2==0){
		                System.out.println(lastIndex+1);
		            }else{
		                System.out.println(lastIndexOfone+1);
		            }
		        }
		    }
		}
	}
}

Zebra Crossing CodeChef Solution in PYPY 3

def solve():

	last_zero, last_one = path.rfind("0") + 1, path.rfind("1") + 1
	

	new_path = path[0]
	count = 0
	for i in range(1, n):
		if path[i] != new_path:
			new_path = path[i]
			count += 1
	
	if count >= k:
		if path[0] == "1":
			if k%2 == 1:
				#end at "0"
				print(last_zero)
			else:
				#end at "1"
				print(last_one)
		else:
			if k%2 == 1:
				#end at "1"
				print(last_one)
			else:
				#end at "0"
				print(last_zero)
	else:
		print(-1)
	

	
	
t = int(input())
 
for _ in range(t):

	n, k = list(map(int, input().split()))
	
	path = input()
	solve()

Zebra Crossing CodeChef Solution in PYTH

t = int(raw_input())
for i in range(t):
	st = raw_input().split()
	N = int(st[0])
	K = int(st[1])
	st = raw_input().strip()
	L = []
	for p in range(1,N):
		if st[p] != st[p-1]:
			L.append(p)
		# endif
	# endfor p
	r = -1
	sz = len(L)
	if K <= sz:
		if K%2 == sz%2:
			r = N
		else:
			r = L[-1]
		# endif
	# endif
	print r
# endfor i

Zebra Crossing CodeChef Solution in C#

using System;
using System.Collections.Generic;

public class Test
{
    
    		private static void Fill(IList<long> list, ref string str)
		{
			checked
	        {
		        list.Clear();
		        var strIdx = 0;
		        long sign = 1;
		        long curr = 0;

		        while (strIdx < str.Length)
		        {
			        if (str[strIdx] == ' ')
			        {
				        list.Add(sign * curr);
				        curr = 0;
				        sign = 1;
			        }
			        else if (str[strIdx] == '-')
			        {
				        sign = -1;
				        curr = 0;
			        }
			        else
			        {
				        curr *= 10;
				        curr += (long)(str[strIdx] - '0');
			        }

			        strIdx++;
		        }

		        list.Add(sign * curr);
	        }
        }

        private interface IInputReader
        {
	        string ReadInput();
        }

        private class ConsoleReader : IInputReader
        {
	        public string ReadInput() => Console.ReadLine().Trim();
        }
    
    
	public static void Main()
	{
					checked
			{
				//var reader = new DebugReader();
				var reader = new ConsoleReader();
				var tests = int.Parse(reader.ReadInput());

				List<long> nk = new List<long>();

				for (int test = 0; test < tests; test++)
				{
					var str = reader.ReadInput();
					Fill(nk, ref str);

					var n = (int) nk[0];
					var k = (int)nk[1];
					str = reader.ReadInput();

					IList<int> tmp = new List<int>(n);

					int l = 0;
					int r = 0;

					while (l < n && r < n)
					{
						r = l;
						while (r < n && str[l] == str[r])
						{
							r++;
						}
						tmp.Add(r - 1);
						l = r;
					}

					if (tmp.Count >= k + 1)
					{
						if (k % 2 == 0)
						{
							if ((tmp.Count - 1) % 2 == 0)
							{
								Console.WriteLine(tmp[tmp.Count - 1] + 1);
							}
							else
							{
								Console.WriteLine(tmp[tmp.Count - 2] + 1);
							}
						}
						else
						{
							if ((tmp.Count - 1) % 2 == 1)
							{
								Console.WriteLine(tmp[tmp.Count - 1] + 1);
							}
							else
							{
								Console.WriteLine(tmp[tmp.Count - 2] + 1);
							}
						}
					}
					else
					{
						Console.WriteLine(-1);
					}
				}
			}
	}
}

Zebra Crossing CodeChef Solution in NODEJS

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here
let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n');    
    main();    
});

function readLine(){
    return inputString[currentLine++];
}

function main(){
    // input in nodeJs
	let test = parseInt(readLine(),10);
	while(test--){
		let n = (readLine());
	//	let k = parseInt(readLine(),10);
	//	let str = String(readLine());
	   n= n.split(' ');
	   n=n.map((e)=>parseInt(e));
	   let N = n[0];
	   let K = n[1];
	   let s = String(readLine());
	 
	 let i=s[0];

	 
	 
	 
	        let flag=0;
            let lastIndex=-1;
            if(K%2==0)
            {
                if(s[0]=='1')
                    lastIndex=s.lastIndexOf('1');
                else
                    lastIndex=s.lastIndexOf('0');
            }
            else
            {
                if(s[0]=='1')
                    lastIndex=s.lastIndexOf('0');
                else
                    lastIndex=s.lastIndexOf('1');
            }
            if(lastIndex==-1)
            {
                console.log(-1);
                continue;
            }
            for(let i=lastIndex;i>0;i--)
            {
                let ch=s[i];
                if(K%2==0 && ch==s[0])
                    K--;
                else if(K%2!=0 && ch!=s[0])
                    K--;
                if(K==0)
                {
                    flag=1;
                    break;
                }
            }
            if(flag==0)
                console.log(-1);
            else
                console.log(lastIndex+1);
        }
}

Zebra Crossing CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k := readTwoNums(reader)
		S, _ := reader.ReadString('\n')
		res := solve(n, k, S)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())

}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, k int, S string) int {
	// n <= 1000
	// if k is even, then last pot must be different from S[0]
	// else must be same
	var cnt int
	for i := 1; i < n; i++ {
		if S[i] != S[i-1] {
			cnt++
		}
	}
	if cnt < k {
		return -1
	}
	// cnt >= k
	bit := S[0]
	if k&1 == 1 {
		if S[0] == '0' {
			bit = '1'
		} else {
			bit = '0'
		}
	}

	for i := n - 1; i >= 0; i-- {
		if S[i] == bit {
			return i + 1
		}
	}
	return -1
}
Zebra Crossing CodeChef Solution Review:

In our experience, we suggest you solve this Zebra Crossing CodeChef 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 Zebra Crossing CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Zebra Crossing CodeChef 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 Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *