You are given a string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in it no more than twice.Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.It can be shown that the answer always exists. If there are multiple answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase consists of a non-empty string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in the string no more than twice. The length of the string doesn't exceed $$$52$$$.

For each testcase, print a single string. Every letter should appear in it the same number of times as it appears in string $$$s$$$. For each pair of letters that appear exactly twice, the distance between the letters in the pair should be the same. If there are multiple answers, print any of them.

NoteIn the first testcase of the example, the only letter that appears exactly twice is letter 'l'. You can rearrange the letters arbitrarily, since there are no distances to compare.In the second testcase of the example, the letters that appear exactly twice are 'a', 'b' and 'c'. Initially, letters 'a' are distance $$$6$$$ apart, letters 'b' are distance $$$4$$$ apart and letters 'c' are distance $$$2$$$ apart. They are not the same, so we have to rearrange the letters. After rearrangement, letters 'a' are distance $$$2$$$ apart, letters 'b' are distance $$$2$$$ apart and letters 'c' are distance $$$2$$$ apart. They are all the same, so the answer is valid.In the third testcase of the example, there are no letters that appear exactly twice. Thus, any rearrangement is valid. Including not changing the string at all.

function reduce(number,denomin){
  var gcd = function gcd(a,b){
    return b ? gcd(b, a%b) : a;
  };
    gcd = gcd(number,denomin);
  return [number/gcd, denomin/gcd];
}
let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var n = lines[0];
    for(j = 1; j <= n; j++){
        var k = lines[j].split('').sort();
        var ans = '';
        for(i = 0; i < k.length; i++){
            ans += k[i];
        }
        console.log(ans);
    }
});

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
    let inp = input.split(/\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++];
    let t = inp[0];
    let i = 1;
    while(t--) {
        let arr = inp[i].split('');
        arr.sort();
        arr.forEach(element => process.stdout.write(element));
        process.stdout.write("\n");
        ++i;
    }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let s = readline();
        output(s.split('').sort().join(''));
    }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var S = nextCharArray();
		S.sort();
		myout(myconv(S, 0));
	}
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var a = ''
        var s = lines[j].split('').sort()
        for(k = 0; k < s.length; k++){
        a += s[k]
        }
        console.log(a)

    }
});

'use strict'
process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

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

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

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(line => {
      return line.trim()
    })

  main()
})

function charsort(s) {
  return s.split('').sort().join('')
}

function main() {
  let t = readLine()
  while (t--) {
    let s = readLine()
    s = charsort(s)
    console.log(s)
  }
}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

process.stdin.on("end", (_) => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  main();
});

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

function main() {
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
    let s = readline()
    let mp = new Map()

    for(let c of s) {
      if(mp.has(c)) mp.set(c, 1 + mp.get(c))
      else mp.set(c, 1)
    }

    let ans = ""

    for(let [key, val] of mp.entries()) {
      if(val === 2)
        ans += key + key
      else
        ans += key
    }

    console.log(ans)
  }
}

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let s = nl.line();
		ans.push(s.split('').sort().join(''));
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

process.stdin.on("end", (_) => {
    inputString = inputString
        .trim()
        .split("\n")
        .map((string) => {
            return string.trim();
        });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Common Template Ends //

// LIBRARY START //

const isOdd = (x) => { return x & 1 }
const isEven = (x) => { return !(x & 1) }

const reverseText = (s) => { return s.split('').reverse().join('') }
const hasDuplicates = (str) => (/([a-z])\1/i).test(str)

const hasDuplicateChar = (str, char) => str.indexOf(char) !== str.lastIndexOf(char)

const isSorted = arr => arr.every((v, i, a) => !i || a[i - 1] <= v);

const findAllIndicesOfChar = (str, char) => {
    str = str.split('')
    let indices = [];
    for (let i = 0; i < str.length; i++) {
        if (str[i] === char) indices.push(i);
    }
    return indices
}

const splitAt = index => x => [x.slice(0, index), x.slice(index)]

const isUpper = str => !/[a-z]/.test(str) && /[A-Z]/.test(str)

const escapeRegExp = (string) => string.replace(/[.*+\-?^$$${}()|[\]\\]/g, '\$$$&')

const replaceAll = (str, find, replace) => str.replace(new RegExp(escapeRegExp(find), 'g'), replace)

const findUnique = (str) => {
    return [...str].reduce((acc, curr) => {
        return acc.includes(curr) ? acc : acc + curr;
    }, "")
}

const unique = (str) => {
    const cleanStr = str.replace(/ /gi, '');
    const set = [...new Set(cleanStr)];
    return set;
}

const sortASC = (array) => {
    // var numArray = new Uint32Array(array)
    // var numArray = new Int32Array(array)
    var numArray = new Float64Array(array)
    numArray = numArray.sort()
    return numArray
}

const removeDuplicates = (array) => [...new Set(array)]

// LIBRARY END

function main() {
    let tc = +readline();
    for (let i = 0; i < tc; i++) {
        let s = readline().split('');
        s.sort();
        s = s.join('');
        console.log(s);
    }
}

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});

	//------------------------------<Solution>-------------------------------//
	let t = inputReader.readNumber();
	//let t = 1;

	function solve() {
	  let s = inputReader.readLine();
	  s = s.split("").sort((a, b) => {
	    if(a > b) return 1;
	    else if(a == b) return 0;
	    else return -1;
	  }).join("");
	  console.log(s);
	}

	while (t--) {
	  solve();
	}

	//------------------------------<Solution>-------------------------------//

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readLine(){
		return _inputLines[_lineNumber++];
	}

	return {
		readNumber,
		readLine,
	}
}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  let tc = parseInt(readline());
  for (let t=0; t<tc; t++) {
      let str = readline()
      let obj = {}
      for (let i=0; i<str.length; i++) {
      if(!obj[str[i]]) {
            obj[str[i]] = 1;
          } else {
           obj[str[i]] += 1;
  }

  }

    let str2 = '';
    for (const elem in obj){
             if(obj[elem] == 2) {

              str2 += elem + elem;

          } else {
             str2 += elem;
      }
     }
      console.log(str2)
      }
  }

process.stdin.setEncoding('utf-8')
const readline = require('readline')

const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    }
)

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        main()
        process.exit(0)
    }
})

function solve(str) {
    const arr = str.split('')
    const mp = new Map()
    const res = [], res2 = [], res3 = []
    arr.forEach((i) => {
        mp.set(i, mp.get(i) ? mp.get(i) + 1 : 1)
        if (mp.get(i) === 2) {
            res.push(i)
        }
    })
    for (let [key, value] of mp.entries()) {
        if (value == 1) {
            res2.push(key)
        }
    }
    res.forEach(i => {
        res3.push(i)
    })
    res2.forEach(i => {
        res3.push(i)
    })
    res.forEach(i => {
        res3.push(i)
    })
    console.log(res3.join(''))
}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])
}

var t = parseInt(readline());
  function solve(){
    var inp = readline().split("")

    inp.sort((a,b) =>{
       if(a>b){
           return 1
       }else if(a < b){
           return -1
       }else{
           return 0
       }
   })
    return inp.join("")
  }

while(t--){
   print(solve())
}

function reduce(number,denomin){
  var gcd = function gcd(a,b){
    return b ? gcd(b, a%b) : a;
  };
    gcd = gcd(number,denomin);
  return [number/gcd, denomin/gcd];
}
let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var n = lines[0];
    for(j = 1; j <= n; j++){
        var h = lines[j];
        var g = reduce(h, 100);
            console.log(g[1]);

    }
});

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
    let inp = input.split(/\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++];
    let t = inp[0];
    console.log(inp);
    let i = 1;
    while(t--) {
        let arr = inp[i].split('');
        arr.sort();
        arr.forEach(element => process.stdout.write(element));
        process.stdout.write("\n");
        ++i;
    }
}


Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum $$$2039 + 2976$$$ would be as shown:   However, Alice evaluates it as shown:   In particular, this is what she does:   add $$$9$$$ and $$$6$$$ to make $$$15$$$, and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$0$$$ $$$9$$$";  add $$$3$$$ and $$$7$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$2$$$ $$$2$$$";  add $$$1$$$, $$$0$$$, and $$$9$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column above the plus sign;  add $$$1$$$, $$$2$$$ and $$$2$$$ to make $$$5$$$;  add $$$1$$$ to make $$$1$$$.  Thus, she ends up with the incorrect result of $$$15005$$$.Alice comes up to Bob and says that she has added two numbers to get a result of $$$n$$$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$. Note that pairs $$$(a, b)$$$ and $$$(b, a)$$$ are considered different if $$$a \ne b$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number Alice shows Bob.

For each test case, output one integer — the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$.

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const s = rl();
		const n = s.length;
		const dp = Array.from(Array(n + 1), _ => Array.from(Array(2), _ => Array(2))); //like int dp [n+1][2][2];
		dp[n] = [[1, 0], [0, 0]];

		for (let i = n - 1; i >= 0; i--) {
			const d = s[i] - 0;
			dp[i][0][0] = dp[i+1][0][0] * (d + 1) + dp[i+1][0][1] * ((d - 1) + 1);
			dp[i][0][1] = dp[i+1][1][0] * (d + 1) + dp[i+1][1][1] * ((d - 1) + 1);
			dp[i][1][0] = dp[i+1][0][0] * (9 - d) + dp[i+1][0][1] * (9 - (d - 1));
			dp[i][1][1] = dp[i+1][1][0] * (9 - d) + dp[i+1][1][1] * (9 - (d - 1));
		}

		console.log(dp[0][0][0] - 2);
	}
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		let n = rn();

		let a = [0, 0], d = 0;
		while (n) {
			let cur = n % 10;
			cur *= 10 ** (d >> 1);
			a[d % 2] += cur;

			n = Math.floor(n / 10);
			d++;
		}

		const ans = (a[0] + 1) * (a[1] + 1) - 2;

		console.log(ans);
	}
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
var input = '';
process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

const f = (a, b) => {
    const sa = a.toString().split('').reverse();
    const sb = b.toString().split('').reverse();
    const buf = {};
    const res = [];
    for (const i of Array(Math.max(sa.length, sb.length)).keys()) {
        res[i] = (parseInt(sa[i]) || 0) + (parseInt(sb[i]) || 0) + (buf[i] || 0);
        if (res[i] >= 10) {
            res[i] -= 10;
            buf[i + 2] = (buf[i + 2] || 0) + 1;
        }
        buf[i] = 0;
    }
    for (const i in buf) {
        if (buf[i] != 0) res[i] = buf[i];
    }
    for (const i of Array(res.length).keys()) {
        if (!(res[i] >= 0)) {
            res[i] = 0;
        }
    }
    return parseInt(res.reverse().join(''));
}

/*
for (const i of Array(100).keys()) {
    const a = Math.floor(Math.random()*1000);
    const b = Math.floor(Math.random()*1000);
    console.log(`${a}, ${b}: ${f(a, b)} - ${a + b} = ${f(a, b) - a - b}`);
}
*/

/*
//const n = 10000;
const n = 2021;

let start = 0;

while (parseInt(start.toString(2).replace(/1/g, 9)) < n) {
    start += 1;
    console.log(parseInt(start.toString(2).replace(/1/g, 9)));
}

console.log(start);
*/

ans = (n) => {
    const a = [];
    const b = [];
    Array.from(n.toString()).map((e, idx) => {
        if (idx % 2 == 0) a.push(e);
        else b.push(e);
    })
    return ((parseInt(a.join('')) || 0) + 1)*((parseInt(b.join('')) || 0) + 1) - 2;
};

const main = (input) => {
    input = input.split('\n');
    const n = +input[0];
    input.shift();
    const res = input.map(e => e.length > 0 ? ans(e) : '').join('\n');
    console.log(res);
}


This problem is same as the next one, but has smaller constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var vmap = kmap.map(function(k) { return hmap[k]; });

    var maxL = Math.max.apply(null, vmap);
    var minL = Math.min.apply(null, vmap);

    if (maxL === minL && minL === 1 || kmap.length === 1) {
        return true;
    }

    var maxValAmm = 0;
    var minValAmm = 0;
    vmap.forEach(function(v) {
        if (v === maxL) {
            maxValAmm++;
        }
        if (v === minL) {
            minValAmm++;
        }
    });

    if (minValAmm === 1 && minL === 1 && maxValAmm + 1 === kmap.length) {
        return true;
    }
    if (maxValAmm === 1 && maxL - minL === 1 && minValAmm + 1 === kmap.length) {
        return true;
    }

    return false;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (!hmap[seq[i - 1]]) delete hmap[seq[i - 1]];
        if (shouldStop()) {
            break;
        }
    }
    print(i - 1);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var summ = hmap[kmap[0]];
    var i = 0;

    for(i; i < kmap.length; i++) {
        if (Math.abs(hmap[kmap[i]] - summ) > 1) {
            break;
        }
    }

    return i === kmap.length;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; --i) {
        hmap[seq[i]] -= 1;
        if (shouldStop()) {
            break;
        }
    }

    print(i);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var summ = hmap[kmap[0]];
    var i = 0;

    for(i; i < kmap.length; i++) {
        if (hmap[kmap[i]] <= 0) continue;
        if (Math.abs(hmap[kmap[i]] - summ) > 1) {
            break;
        }
    }

    return i === kmap.length;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (hmap[seq[i - 1]]) {
            x--;
        }
        if (shouldStop()) {
            break;
        }
    }
    print(x);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var difs = [];
    var i = 0;

    for(i; i < kmap.length; i++) {
        if (difs.indexOf(hmap[kmap[i]]) === -1) {
            difs.push(hmap[kmap[i]]);
            if (difs.length > 2) break;
        }
    }
    return difs.length === 2;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (!hmap[seq[i - 1]]) delete hmap[seq[i - 1]];
        if (shouldStop()) {
            break;
        }
    }
    print(i - 1);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var vmap = kmap.map(function(k) { return hmap[k]; });

    var maxL = Math.max.apply(null, vmap);
    var minL = Math.min.apply(null, vmap);

    if (maxL === minL && minL === 1) {
        return true;
    }

    var maxValAmm = 0;
    var minValAmm = 0;
    vmap.forEach(function(v) {
        if (v === maxL) {
            maxValAmm++;
        }
        if (v === minL) {
            minValAmm++;
        }
    });

    if (minValAmm === 1 && minL === 1 && maxValAmm + 1 === kmap.length) {
        return true;
    }

    return false;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (!hmap[seq[i - 1]]) delete hmap[seq[i - 1]];
        if (shouldStop()) {
            break;
        }
    }
    print(i - 1);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var vmap = kmap.map(function(k) { return hmap[k]; });

    var maxL = Math.max.apply(null, vmap);
    var minL = Math.min.apply(null, vmap);

    if (maxL === minL && minL === 1) {
        return true;
    }

    var maxValAmm = 0;
    var minValAmm = 0;
    vmap.forEach(function(v) {
        if (v === maxL) {
            maxValAmm++;
        }
        if (v === minL) {
            minValAmm++;
        }
    });

    if (minValAmm === 1 && minL === 1 && maxValAmm + 1 === kmap.length) {
        return true;
    }
    if (maxValAmm === 1 && maxL - minL === 1 && minValAmm + 1 === kmap.length) {
        return true;
    }

    return false;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (!hmap[seq[i - 1]]) delete hmap[seq[i - 1]];
        if (shouldStop()) {
            break;
        }
    }
    print(i - 1);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var vmap = kmap.map(function(k) { return hmap[k]; });

    var maxL = Math.max.apply(null, vmap);
    var minL = Math.min.apply(null, vmap);

    if (maxL === minL && minL === 1) {
        return true;
    }

    var maxValAmm = 0;
    var minValAmm = 0;
    vmap.forEach(function(v) {
        if (v === maxL) {
            maxValAmm++;
        }
        if (v === minL) {
            minValAmm++;
        }
    });

    if (minValAmm === 1 && maxValAmm + 1 === kmap.length) {
        return true;
    }

    if (maxValAmm === 1 && maxL - minL === 1) {
        return true;
    }

    return false;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (!hmap[seq[i - 1]]) delete hmap[seq[i - 1]];
        if (shouldStop()) {
            break;
        }
    }
    print(i - 1);
}

var n = parseInt(readline());

var hmap = {};
var seq = readline().split(' ').map(function(v) {

    if (!hmap[v]) {
        hmap[v] = 1;
    } else {
        hmap[v] += 1;
    }
    return v;
});

var x = n;

var i = n;

function shouldStop() {
    var kmap = Object.keys(hmap);
    var i = 0;
    var sizes = [];
    for(i; i < kmap.length; i++) {
        if (sizes.indexOf(hmap[kmap[i]]) === -1) {
            sizes.push(hmap[kmap[i]]);
            if (sizes.length > 2) {
                break;
            }
        }
    }
    if (sizes.length === 1 && sizes[0] === 1) return true;
    if (sizes.length === 2) {
        if (sizes[0] - sizes[1] === 1 || sizes[0] === 1 || sizes[1] === 1) {
            return true;
        }
    }
    return false;
}

if (shouldStop()) {
    print(x);
} else {
    for (i; i > 0; i--) {
        hmap[seq[i - 1]]--;
        if (!hmap[seq[i - 1]]) delete hmap[seq[i - 1]];
        if (shouldStop()) {
            break;
        }
    }
    print(i - 1);
}


The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:   ti < ti + 1 for each odd i < n;  ti > ti + 1 for each even i < n. For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.

The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.

Print the number of ways to swap two elements exactly once in order to get a nice sequence.

NoteIn the first sample, there are two ways to get a nice sequence with one swap:   Swap t2 = 8 with t4 = 7.  Swap t1 = 2 with t5 = 7. In the second sample, there is only one way — Limak should swap t1 = 200 with t4 = 50.

"use strict";

function main()
{
  readline();

  var numbers = readline().split(" ").map(x => parseInt(x, 10));
  var count = numbers.length;

  var errors = [];
  for (var i=0 ; i<count ; i++)
  {
    if (!canPut(i, numbers[i]))
    {
      errors.push(i);

      if (errors.length > 6)
      {
        print("0");
        return;
      }
    }
  }

  var out = 0;
  var swaps = new Set();

  for (var i=0 ; i<errors.length ; i++)
  {
    var test = errors[i];

    var z = numbers[test];

    for (var j=0 ; j<count ; j++)
    {
      if (test == j)
      {
        continue;
      }

      var y = numbers[j];

      numbers[test] = y;
      numbers[j] = z;

      if (canPut(test, y) && canPut(j, z))
      {
        var e = errors.reduce(filter, 0);

        if (e == errors.length)
        {
          swaps.add(Math.min(test,j) + "." + Math.max(test,j));
        }
      }

      numbers[j] = y;
    }

    numbers[test] = z;
  }

  print(swaps.size);

  function filter(a, b)
  {
    return a + ((j-1<=b && j+1>=b) || (test-1<=b && test+1>=b));
  }

  function canPut(at, v)
  {
    var pre = at - 1;
    var post = at + 1;

    var even = (at & 1) == 0;

    if (pre >= 0)
    {
      var diff = v - numbers[pre];

      if (diff == 0 || ((diff > 0) == even))
      {
        return false;
      }
    }

    if (post < count)
    {
      var diff = numbers[post] - v;

      if (diff == 0 || ((diff < 0) == even))
      {
        return false;
      }
    }

    return true;
  }

}

main();


Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \leq 200\,000$$$) — the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \ldots, k_q$$$ ($$$1 \leq k_i \leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.

Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.

NoteIn the first example:   after the 1-st minute, the 1-st and 2-nd warriors die.  after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive.  after the 3-rd minute, the 1-st warrior dies.  after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1.  after the 5-th minute, the 2-nd warrior dies.

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}

var nq = readline().split(' ');
var n = +nq[0], q = +nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(+item));
ki = readline().split(' ').map(item => Math.floor(+item));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( hi- (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => Number(item));
ki = readline().split(' ').map(item => Number(item));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
if(n === 145000) print('!' + ai[0] + ai[1] + ai[2]);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i !== 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid = hi - parseInt( (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
if(n === 145000) print('!' , ki[0] , ki[1] , ki[2]);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i !== 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
//print(ai);
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid = hi - (~~( (hi - lo) / 2 ));
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    if(ans === n) sum = 0;
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid = hi - parseInt( (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
if(n === 145000) print('!' , ki[0] , ki[1] , ki[2]);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}