A - Yet Another AB Problem
Source: atcoder
Difficulty: 400

Problem Statement
You are given two strings
S
and
T
of length
N
consisting of
A
and
B
. Let
S_i
denote the
i
-th character from the left of
S
.
You can repeat the following operation any number of times, possibly zero:
Choose integers
i
and
j
such that
1\leq i < j \leq N
. Replace
S_i
with
A
and
S_j
with
B
.
Determine if it is possible to make
S
equal
T
. If it is possible, find the minimum number of operations required.
Constraints
2 \leq N \leq 2 \times 10^5
Each of
S
and
T
is a string of length
N
consisting of
A
and
B
.
All input numbers are integers.
Input
The input is given from Standard Input in the following format:
N
S
T
Output
If it is impossible to make
S
equal
T
, print
-1
.
Otherwise, print the minimum number of operations required to do so.
Sample Input 1
5
BAABA
AABAB
Sample Output 1
2
Performing the operation with
i=1
and
j=3
changes
S
to
AABBA
.
Performing the operation with
i=4
and
j=5
changes
S
to
AABAB
.
Thus, you can make
S
equal
T
with two operations. It can be proved that this is the minimum number of operations required, so the answer is
2
.
Sample Input 2
2
AB
BA
Sample Output 2
-1
It can be proved that no matter how many operations you perform, you cannot make
S
equal
T
.

C++ solution:
/**
*  Problem Name: AD_Yet_Another_AB_Problem
*  Author: MJ
*  Created: 06 May 2025, Tuesday (14:55:57)...
**/

#include<bits/stdc++.h>
using namespace std;

#define int int64_t
#define nl '\n' 

void answer_to_the_question(){
    int n;      string s,t;         cin>>n>>s>>t;

    for(int i=0;i<n;i++){
        if(t[i]=='A')  break;

        if(s[i]=='A' && t[i]=='B'){
            cout<<-1<<nl;
            return;
        }
    }

    for(int i=n-1;i>=0;i--){
        if(t[i]=='B')  break;

        if(s[i]=='B' && t[i]=='A'){
            cout<<-1<<nl;
            return;
        }
    }

    int ans=0,op=0;
    for(int i=0;i<n;i++){
        if(s[i]=='B' && t[i]=='A'){
            op++;
        }

        if(s[i]=='A' && t[i]=='B'){
            if(op){
                op--;
            }
            ans++;
        }
    }
    ans+=op;

    cout<<ans<<nl;
}

int32_t main(){
    ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

    answer_to_the_question();

    return 0;
}

// Hi

Go solution:
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

func init() {
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Split(bufio.ScanWords)
}

func main() {
	//defer flush()

	nxi()
	s, t := nxs(), nxs()

	ans, pair := 0, 0
	pre, suf := false, false

	for i := range s {
		if t[i] == 'A' {
			pre = true
		}
		if t[i] == 'B' {
			suf = false
		}
		if s[i] == 'A' && t[i] == 'B' {
			if !pre {
				fmt.Println("-1")
				return
			}
			if pair > 0 {
				pair--
			} else {
				ans++
			}
		}
		if s[i] == 'B' && t[i] == 'A' {
			ans++
			pair++
			suf = true
		}
	}

	if suf {
		fmt.Println("-1")
	} else {
		fmt.Println(ans)
	}
}

func nxi() int {
	sc.Scan()
	return atoi(sc.Text())
}

func nxs() string {
	sc.Scan()
	return sc.Text()
}

func atoi(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}

func flush() {
	err := wr.Flush()
	if err != nil {
		panic(err)
	}
}

Java solution:
import java.io.*;
import java.lang.reflect.Array;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.IntFunction;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public final class Main {
    public static void main(String[] args) throws IOException {
        run(System.in, new PrintStream(new BufferedOutputStream(System.out), false, StandardCharsets.UTF_8));
    }

    @SuppressWarnings({"DuplicatedCode", "SameParameterValue"})
    static void run(InputStream in, PrintStream out) throws IOException {
        FastScanner scanner = new FastScanner(in);

        scanner.skipToNextLine();
        var s = scanner.nextLine();
        var t = scanner.nextLine();
        out.println(solve(s, t));

        out.flush();
    }

    static int solve(String s, String t) {
        var firstError = -1;
        var lastError = -1;
        var errors = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != t.charAt(i)) {
                errors++;
                if (firstError == -1) {
                    firstError = i;
                }

                lastError = i;
            }
        }

        if (errors == 0) {
            return 0;
        }

        if (s.charAt(firstError) == 'A' && s.indexOf('A') == firstError) {
            return -1;
        }

        if (s.charAt(lastError) == 'B' && s.lastIndexOf('B') == lastError) {
            return -1;
        }

        var pairs = 0;
        var bs = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != t.charAt(i)) {
                if (s.charAt(i) == 'B') {
                    bs++;
                } else {
                    if (bs > 0) {
                        pairs++;
                        bs--;
                    }
                }
            }
        }

        return errors - pairs;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static void printIntsLn(PrintStream out, int... ints) {
        printIntsLn(out, ints, " ");
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static void printIntsLn(PrintStream out, int[] ints, String separator) {
        for (int i = 0; i < ints.length; i++) {
            if (i != 0) {
                out.print(separator);
            }

            out.print(ints[i]);
        }

        out.println();
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static void printLongsLn(PrintStream out, long... longs) {
        printLongsLn(out, longs, " ");
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static void printLongsLn(PrintStream out, long[] longs, String separator) {
        for (int i = 0; i < longs.length; i++) {
            if (i != 0) {
                out.print(separator);
            }

            out.print(longs[i]);
        }

        out.println();
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    @SafeVarargs
    static <T> void printObjectsLn(PrintStream out, T... objects) {
        printObjectsLn(out, List.of(objects), " ");
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static void printObjectsLn(PrintStream out, Collection<?> objects) {
        printObjectsLn(out, objects, " ");
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static void printObjectsLn(PrintStream out, Collection<?> objects, String separator) {
        var first = true;
        for (Object object : objects) {
            if (!first) {
                out.print(separator);
            }

            out.print(object);
            first = false;
        }

        out.println();
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static int minOf(int... is) {
        if (is.length == 0) {
            throw new IllegalArgumentException();
        }

        var res = Integer.MAX_VALUE;
        for (int i : is) {
            res = Math.min(res, i);
        }
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static int maxOf(int... is) {
        if (is.length == 0) {
            throw new IllegalArgumentException();
        }

        var res = Integer.MIN_VALUE;
        for (int i : is) {
            res = Math.max(res, i);
        }
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static long minOf(long... is) {
        if (is.length == 0) {
            throw new IllegalArgumentException();
        }

        var res = Long.MAX_VALUE;
        for (long i : is) {
            res = Math.min(res, i);
        }
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static long maxOf(long... is) {
        if (is.length == 0) {
            throw new IllegalArgumentException();
        }

        var res = Long.MIN_VALUE;
        for (long i : is) {
            res = Math.max(res, i);
        }
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    record MinMax<T>(T min, T max) {
        static MinMax<Integer> from(int... is) {
            if (is.length == 0) {
                throw new IllegalArgumentException();
            }

            var min = Integer.MAX_VALUE;
            var max = Integer.MIN_VALUE;
            for (int x : is) {
                min = Math.min(min, x);
                max = Math.max(max, x);
            }

            return new MinMax<>(min, max);
        }

        static MinMax<Long> from(long... is) {
            if (is.length == 0) {
                throw new IllegalArgumentException();
            }

            var min = Long.MAX_VALUE;
            var max = Long.MIN_VALUE;
            for (long x : is) {
                min = Math.min(min, x);
                max = Math.max(max, x);
            }

            return new MinMax<>(min, max);
        }
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static <T> ArrayList<T> fillList(int n, Supplier<T> supplier) {
        return fillList(n, ignore -> supplier.get());
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static <T> ArrayList<T> fillList(int n, IntFunction<T> valueAt) {
        var res = new ArrayList<T>(n);
        for (int i = 0; i < n; i++) {
            res.add(valueAt.apply(i));
        }

        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static <T> T[] fillArray(int n, Class<T> clazz, Supplier<T> supplier) {
        return fillArray(n, clazz, ignore -> supplier.get());
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static <T> T[] fillArray(int n, Class<T> clazz, IntFunction<T> valueAt) {
        @SuppressWarnings("unchecked") var res = (T[]) Array.newInstance(clazz, n);

        for (int i = 0; i < n; i++) {
            res[i] = valueAt.apply(i);
        }

        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused", "SameParameterValue"})
    static <T> T[] fillArray(int n, T value) {
        @SuppressWarnings("unchecked") var res = (T[]) Array.newInstance(value.getClass(), n);
        Arrays.fill(res, value);
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static int[] fillIntArray(int n, IntUnaryOperator valueAt) {
        var res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = valueAt.applyAsInt(i);
        }
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static int[] fillIntArray(int n, int value) {
        var res = new int[n];
        Arrays.fill(res, value);
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static long[] fillLongArray(int n, LongUnaryOperator valueAt) {
        var res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = valueAt.applyAsLong(i);
        }
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static long[] fillLongArray(int n, long value) {
        var res = new long[n];
        Arrays.fill(res, value);
        return res;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    record BinaryString(BitSet bits, int length) {
        public BinaryString {
            if (length < 0) throw new IndexOutOfBoundsException("" + length);
        }

        @Override
        public String toString() {
            return IntStream.range(0, length)
                    .mapToObj(i -> bits.get(i) ? "1" : "0")
                    .collect(Collectors.joining());
        }
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    record BinaryGrid(BitSet[] bits, int w) {
        BinaryGrid {
            if (w < 0) throw new IndexOutOfBoundsException("w=" + w);
        }

        int h() {
            return bits.length;
        }

        BitSet row(int i) {
            return bits[i];
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            BinaryGrid that = (BinaryGrid) o;

            if (w != that.w) return false;
            return Arrays.equals(bits, that.bits);
        }

        @Override
        public int hashCode() {
            int result = Arrays.hashCode(bits);
            result = 31 * result + w;
            return result;
        }

        @Override
        public String toString() {
            return Arrays.stream(bits, 0, h())
                    .map(row -> IntStream.range(0, w).mapToObj(j -> row.get(j) ? "1" : "0").collect(Collectors.joining()))
                    .collect(Collectors.joining("\n"));
        }
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static final class Adj {
        static ArrayList<ArrayList<Integer>> undirected(int n, int[][] edges) {
            return undirected(n, edges, 1);
        }

        @SuppressWarnings("SameParameterValue")
        static ArrayList<ArrayList<Integer>> undirected(int n, int[][] edges, int offset) {
            var res = fillList(n, () -> new ArrayList<Integer>(1));

            for (int[] edge : edges) {
                res.get(edge[0] - offset).add(edge[1] - offset);
                res.get(edge[1] - offset).add(edge[0] - offset);
            }

            return res;
        }
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static long gcd(long a, long b) {
        while (b != 0) {
            var bb = a % b;
            a = b;
            b = bb;
        }

        return a;
    }

    @SuppressWarnings({"DuplicatedCode", "unused"})
    static int gcd(int a, int b) {
        while (b != 0) {
            var bb = a % b;
            a = b;
            b = bb;
        }

        return a;
    }


    @SuppressWarnings({"DuplicatedCode", "unused"})
    static final class FastScanner {
        private final InputStream in;
        private final byte[] buf = new byte[4 * 1024];
        private int a = 0;
        private int b = 0;

        FastScanner(InputStream in) {
            this.in = in;
        }

        byte nextByte() throws IOException {
            if (a < b) {
                byte v = buf[a];
                a += 1;
                return v;
            } else {
                b = in.read(buf);

                if (b < 0) {
                    throw new EOFException();
                } else {
                    a = 0;
                    return nextByte();
                }
            }
        }

        boolean hasNext() throws IOException {
            if (a < b) return true;
            else if (b < 0) return false;
            else {
                b = in.read(buf);
                a = 0;
                return hasNext();
            }
        }

        char nextChar() throws IOException {
            return (char) nextByte();
        }

        char nextNonWhitespaceChar() throws IOException {
            while (true) {
                var c = nextChar();
                if (!Character.isWhitespace(c)) {
                    return c;
                }
            }
        }

        long nextLong() throws IOException {
            while (true) {
                char c = nextChar();

                if (c == '-') {
                    c = nextChar();
                    if (isAsciiDigit(c)) {
                        return Math.negateExact(nextUlongImpl(c));
                    }
                } else if (isAsciiDigit(c)) {
                    return nextUlongImpl(c);
                }
            }
        }

        long[] nextLongs(int n) throws IOException {
            long[] res = new long[n];

            for (int i = 0; i < n; ++i) {
                res[i] = nextLong();
            }

            return res;
        }

        long[][] nextLongs(int rows, int cols) throws IOException {
            long[][] res = new long[rows][cols];

            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    res[i][j] = nextLong();
                }
            }

            return res;
        }

        long nextUlong() throws IOException {
            long res = nextLong();
            if (res < 0) throw new IllegalArgumentException("Expected a positive number, but got " + res);
            return res;
        }

        long[] nextUlongs(int n) throws IOException {
            long[] res = new long[n];

            for (int i = 0; i < n; ++i) {
                res[i] = nextUlong();
            }

            return res;
        }

        long[][] nextUlongs(int rows, int cols) throws IOException {
            long[][] res = new long[rows][cols];

            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    res[i][j] = nextUlong();
                }
            }

            return res;
        }

        int nextInt() throws IOException {
            return Math.toIntExact(nextLong());
        }

        int[] nextInts(int n) throws IOException {
            int[] res = new int[n];

            for (int i = 0; i < n; ++i) {
                res[i] = nextInt();
            }

            return res;
        }

        int[][] nextInts(int rows, int cols) throws IOException {
            int[][] res = new int[rows][cols];

            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    res[i][j] = nextInt();
                }
            }

            return res;
        }

        int nextUint() throws IOException {
            return Math.toIntExact(nextUlong());
        }

        int[] nextUints(int n) throws IOException {
            int[] res = new int[n];

            for (int i = 0; i < n; ++i) {
                res[i] = nextUint();
            }

            return res;
        }

        int[][] nextUints(int rows, int cols) throws IOException {
            int[][] res = new int[rows][cols];

            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    res[i][j] = nextUint();
                }
            }

            return res;
        }

        <T> T[] nextObjects(int n, Class<T> clazz, IOExceptionThrowingSupplier<T> supplier) throws IOException {
            @SuppressWarnings("unchecked") T[] ret = (T[]) Array.newInstance(clazz, n);
            for (int i = 0; i < n; i++) {
                ret[i] = supplier.get();
            }

            return ret;
        }

        String nextLine() throws IOException {
            StringBuilder sb = new StringBuilder();
            char c = nextChar();

            while (c != '\n') {
                sb.append(c);

                if (!hasNext()) {
                    break;
                } else {
                    c = nextChar();
                }
            }

            if (!sb.isEmpty() && c == '\n' && sb.charAt(sb.length() - 1) == '\r') {
                sb.setLength(sb.length() - 1);
            }

            return sb.toString();
        }

        String[] nextLines(int n) throws IOException {
            if (n < 0) {
                n = nextUint();
                skipToNextLine();
            }

            return nextObjects(n, String.class, this::nextLine);
        }

        String[] nextLines() throws IOException {
            return nextLines(-1);
        }

        void skipToNextLine() throws IOException {
            //noinspection StatementWithEmptyBody
            while (nextChar() != '\n') {
                // just skip to next character
            }
        }

        BinaryString nextBinaryString() throws IOException {
            return nextBinaryString('1');
        }

        BinaryString nextBinaryString(char cTrue) throws IOException {
            return nextBinaryStringImpl(cTrue, -1);
        }

        BinaryString nextBinaryString(char cTrue, int length) throws IOException {
            if (length < 0) throw new IndexOutOfBoundsException("" + length);
            return nextBinaryStringImpl(cTrue, length);
        }

        BinaryGrid nextBinaryGrid(char cTrue) throws IOException {
            return nextBinaryGridImpl(cTrue, -1, -1);
        }

        BinaryGrid nextBinaryGrid(char cTrue, int h, int w) throws IOException {
            return nextBinaryGridImpl(cTrue, h, w);
        }

        private BinaryGrid nextBinaryGridImpl(char cTrue, int h, int w) throws IOException {
            if (h < 0) {
                h = nextUint();
                w = nextUint();

                if (h > 0) {
                    skipToNextLine();
                }
            }

            var bits = new BitSet[h];
            for (int i = 0; i < h; i++) {
                var row = new BitSet(w);

                for (int j = 0; j < w; j++) {
                    if (nextChar() == cTrue) {
                        row.set(j);
                    }
                }

                bits[i] = row;

                if (i != h - 1 || hasNext()) {
                    skipToNextLine();
                }
            }

            return new BinaryGrid(bits, w);
        }

        private BinaryString nextBinaryStringImpl(char cTrue, int length) throws IOException {
            if (length < 0) {
                length = nextUint();
                skipToNextLine();
            }

            BitSet bits = new BitSet(length);
            for (int i = 0; i < length; ++i) {
                if (nextChar() == cTrue) {
                    bits.set(i);
                }
            }

            return new BinaryString(bits, length);
        }

        private long nextUlongImpl(char firstDigit) throws IOException {
            long res = 0;
            char c = firstDigit;

            do {
                long res2 = 10 * res + (c - '0');
                if (res2 >= res) {
                    res = res2;
                } else {
                    throw new ArithmeticException("Long overflow");
                }

                if (hasNext()) {
                    c = nextChar();
                } else {
                    c = 0;
                }
            } while (isAsciiDigit(c));

            if (c != 0 && !isAsciiDigit(c)) {
                a -= 1;
            }

            return res;
        }

        private static boolean isAsciiDigit(char c) {
            return '0' <= c && c <= '9';
        }
    }

    interface IOExceptionThrowingSupplier<T> {
        T get() throws IOException;
    }
}

JavaScript solution:
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextssort(n,a){return a?cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>b-a):cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>a-b);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}
var streams=[];function print(s){streams.push(s);}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));
if(streams.length)console.log(streams.join("\n"));

function main(){
  var q = 1;
  while(q--)print(solve());
}

function solve(){
  var n = next();
  var s = nextstr();
  var t = nextstr();
  if(s === t)return 0;
  var ans = 0;
  var a = 0, b = 0, bx = n-1;
  while(a < n){
    if(t[a] === "A")break;
    a++;
  }
  if(a === n)return -1;
  while(bx >= 0){
    if(t[bx] === "B")break;
    bx--;
  }
  if(bx === -1)return -1;
  var ax = a;
  for(;b < n; b++){
    if(s[b] === "A" && t[b] === "B"){
      if(b < ax)return -1;
      while(a < b){
        if(s[a] === "B" && t[a] === "A"){a++;break;}
        a++;
      }
      ans++;
    }
  }
  for(; a < n; a++){
    if(s[a] === "B" && t[a] === "A"){
      if(a > bx)return -1;
      ans++;
    }
  }
  return ans;
}

Python solution:
def main():
    N = int(input())
    S = input()
    T = input()
    for i in range(N):
        if T[i] == "B" and S[i] == "A":
            print(-1)
            return
        if T[i] == "A":
            break
    for i in range(N - 1, -1, -1):
        if T[i] == "A" and S[i] == "B":
            print(-1)
            return
        if T[i] == "B":
            break
    A = 0
    B = 0
    for i in range(N):
        if S[i] != T[i]:
            if S[i] == "B":
                A += 1
            else:
                B += 1
                if A > 0:
                    A -= 1
    print(A + B)


if __name__ == "__main__":
    main()

Ruby solution:
# debug = true
debug = false
A_BYTE,B_BYTE ="AB".bytes
INPUT_LENGTH = gets.to_i
S_BYTES = gets.chomp.bytes
T_BYTES = gets.chomp.bytes
S_TALLY = S_BYTES.tally
T_TALLY = T_BYTES.tally
s_a_t_a_indexes = []
s_a_t_b_indexes = []
s_b_t_a_indexes = []
s_b_t_b_indexes = []
answer = 0
S_BYTES.each_with_index do |tmp_s, i|
  tmp_t = T_BYTES[i]
  case tmp_s
  when A_BYTE
    case tmp_t
    when A_BYTE
      s_a_t_a_indexes << i
    when B_BYTE
      s_a_t_b_indexes << i
    end
  when B_BYTE
    case tmp_t
    when A_BYTE
      s_b_t_a_indexes << i
    when B_BYTE
      s_b_t_b_indexes << i
    end
  end
end

answer = 0
new_s_a_t_b_indexes = []
new_s_b_t_a_indexes = []
while (s_b_t_a_index = s_b_t_a_indexes.shift)
  while (s_a_t_b_index = s_a_t_b_indexes.shift) && s_a_t_b_index < s_b_t_a_index
    new_s_a_t_b_indexes << s_a_t_b_index
  end
  if s_a_t_b_index 
    answer += 1 
    s_a_t_a_indexes << s_b_t_a_index
    s_b_t_b_indexes << s_a_t_b_index
  else 
    new_s_b_t_a_indexes << s_b_t_a_index
  end
end
new_s_a_t_b_indexes.concat s_a_t_b_indexes
p [s_a_t_a_indexes, new_s_a_t_b_indexes, new_s_b_t_a_indexes, s_b_t_b_indexes] if debug
if new_s_a_t_b_indexes.empty? && new_s_b_t_a_indexes.empty?
  puts answer
  exit
end
p [new_s_a_t_b_indexes.min, s_a_t_a_indexes.min] if debug
if new_s_a_t_b_indexes.any? && (new_s_a_t_b_indexes.min < (s_a_t_a_indexes.min || Float::INFINITY))
  puts -1
  exit
end
answer += new_s_a_t_b_indexes.size

if new_s_b_t_a_indexes.any? && (new_s_b_t_a_indexes.max > (s_b_t_b_indexes.max || -1))
  puts -1
  exit
end
answer += new_s_b_t_a_indexes.size
puts answer