Open In App

Find and return index of given String in a Multidimensional Array

Last Updated : 26 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a multidimensional array stringArr of strings and a keyString to be found, the task is to return the coordinates/indexes of that key string in the array.

Example:

Input: stringArr[][] = { { “a”, “h”, “b”}, {“c”, “d”, “e”}, {“g”, “t”, “r”} }, keyString = “e”
Output = {1, 2}
Explanation: Following the 0-based indexing the keyString is present at (1, 2) in the multidimensional array.

Approach: Follow the steps to find the coordinates/indexes of a string in a multidimensional array:

  • Firstly, iterate over all the elements in the array as checking each element in first row, then second row and so on. 
  • Then if the keyString is found in the array, simply return the indexes 
  • else just return -1 as the indices.

Below is the implementation of the above approach:

C++




// CPP Program to return indices of a given
// string from the multidimensional array
#include <bits/stdc++.h>
using namespace std;
 
// Method to return an array of indices
// of keyString
vector<int> findIndex(vector<vector<string> > stringArr,
                      string keyString)
{
 
    // Initialising result array to -1
    // in case keyString is not found
    vector<int> result{ -1, -1 };
 
    // Iteration over all the elements
    // of the 2-D array
 
    // Rows
    for (int i = 0; i < stringArr.size(); i++) {
 
        // Columns
        for (int j = 0; j < stringArr[i].size(); j++) {
 
            // If keyString is found
            if (stringArr[i][j] == keyString) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
 
    // If keyString is not found
    // then -1 is returned
    return result;
}
 
// Driver Code
int main()
{
 
    // Given string array
    vector<vector<string> > stringArr{ { "a", "h", "b" },
                                       { "c", "d", "e" },
                                       { "g", "t", "r" } };
 
    // Given key String to be found
    string keyString = "e";
 
    // Calling the method which
    // returns an array of indices
    vector<int> result = findIndex(stringArr, keyString);
 
    // Printing the indices returned
    cout << "The indices are: ";
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
}


Java




// Java Program to return indices of a given string
// from the multidimensional string array
 
public class Main {
    // method to return an array of indices of keyString
    public static int[] findIndex(String stringArr[][],
                                  String keyString)
    {
        // initialising result array to -1 in case keyString
        // is not found
        int result[] = { -1, -1 };
        // iteration over all the elements of the 2-D array
        // rows
        for (int i = 0; i < stringArr.length; i++) {
            // columns
            for (int j = 0; j < stringArr[i].length; j++) {
                // if keyString is found
                if (stringArr[i][j].equals(keyString)) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        // if keyString is not found then -1 is returned
        return result;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // given string array
        String[][] stringArr = { { "a", "h", "b" },
                                 { "c", "d", "e" },
                                 { "g", "t", "r" } };
        // given key String to be found
        String keyString = "e";
        // calling the method which returns an array of
        // indices
        int[] result = findIndex(stringArr, keyString);
        // printing the indices returned
        System.out.print("The indices are:- ");
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i] + " ");
        }
    }
}


Python3




#  Python Program to return indices of a given
#  string from the multidimensional array
 
#  Method to return an array of indices
#  of keyString
 
def findIndex(stringArr, keyString):
 
    #  Initialising result array to -1
    #  in case keyString is not found
    result = []
 
    #  Iteration over all the elements
    #  of the 2-D array
 
    #  Rows
    for i in range(len(stringArr)):
 
        #  Columns
        for j in range(len(stringArr[i])):
            #  If keyString is found
            if stringArr[i][j] == keyString:
                result.append(i)
                result.append(j)
                return result
    result.append(-1)
    result.append(-1)
    #  If keyString is not found
    #  then -1 is returned
    return result
 
 
   
# Driver Code
# Given string array
stringArr = [["a", "h", "b"],
             ["c", "d", "e"],
             ["g", "t", "r"]]
 
# Given key String to be found
keyString = "e"
 
# Calling the method which
# returns an array of indices
result = findIndex(stringArr, keyString)
 
# Printing the indices returned
print("The indices are:", result[0], result[1])
 
# This code has been contributed by Sachin Sahara (sachin801)


C#




// C# Program to return indices of a given string
// from the multidimensional string array
 
using System;
 
public class GFG
{
   
    // method to return an array of indices of keyString
    public static int[] findIndex(string [,] stringArr,
                                  string keyString)
    {
       
        // initialising result array to -1 in case keyString
        // is not found
        int []result = { -1, -1 };
       
        // iteration over all the elements of the 2-D array
        // rows
        for (int i = 0; i < stringArr.Length; i++)
        {
           
            // columns
            for (int j = 0; j < stringArr.GetLength(0); j++)
            {
               
                // if keyString is found
                if (stringArr[i,j].Equals(keyString)) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
       
        // if keyString is not found then -1 is returned
        return result;
    }
 
    // Driver Code
    public static void Main(string []args)
    {
       
        // given string array
        string[,] stringArr = { { "a", "h", "b" },
                                 { "c", "d", "e" },
                                 { "g", "t", "r" } };
       
        // given key String to be found
        string keyString = "e";
       
        // calling the method which returns an array of
        // indices
        int[] result = findIndex(stringArr, keyString);
       
        // printing the indices returned
        Console.Write("The indices are:- ");
        for (int i = 0; i < result.Length; i++) {
            Console.Write(result[i] + " ");
        }
    }
}
 
// This code is contributed by AnkThon


Javascript




<script>
 
// JavaScript Program to return indices of a given
// string from the multidimensional array
 
 
// Method to return an array of indices
// of keyString
function findIndex(stringArr,keyString)
{
 
    // Initialising result array to -1
    // in case keyString is not found
    let result = [ -1, -1 ];
 
    // Iteration over all the elements
    // of the 2-D array
 
    // Rows
    for (let i = 0; i < stringArr.length; i++) {
 
        // Columns
        for (let j = 0; j < stringArr[i].length; j++) {
 
            // If keyString is found
            if (stringArr[i][j] == keyString) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
 
    // If keyString is not found
    // then -1 is returned
    return result;
}
 
// Driver Code
 
// Given string array
let stringArr = [[ "a", "h", "b" ],
                [ "c", "d", "e" ],
                [ "g", "t", "r" ]];
 
// Given key String to be found
let keyString = "e";
 
// Calling the method which
// returns an array of indices
let result = findIndex(stringArr, keyString);
 
// Printing the indices returned
document.write("The indices are: ");
for (let i = 0; i < result.length; i++) {
    document.write(result[i]," ");
}
 
// This code is contributed by shinjanpatra
 
</script>


Output

The indices are: 1 2 





Time Complexity: O(N2)

Auxiliary Space: O(1)

Approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
pair<int, int>
findIndex(const vector<vector<string> >& stringArr,
          const string& keyString)
{
    vector<string> flattenedArr;
    for (const auto& row : stringArr) {
        flattenedArr.insert(flattenedArr.end(), row.begin(),
                            row.end());
    }
 
    auto it = find(flattenedArr.begin(), flattenedArr.end(),
                   keyString);
    if (it != flattenedArr.end()) {
        int index = distance(flattenedArr.begin(), it);
        int rows = stringArr.size();
        int cols = stringArr[0].size();
        return { index / cols, index % cols };
    }
 
    return { -1, -1 };
}
 
int main()
{
    std::vector<std::vector<std::string> > stringArr{
        { "a", "h", "b" },
        { "c", "d", "e" },
        { "g", "t", "r" }
    };
 
    string keyString = "e";
 
    pair<int, int> result = findIndex(stringArr, keyString);
 
    cout << "The indices are: " << result.first << ", "
         << result.second << endl;
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Program {
 
    public static class Tuple<X, Y> {
        public final X x;
        public final Y y;
        public Tuple(X x, Y y) {
            this.x = x;
            this.y = y;
        }
    }
 
    public static Tuple<Integer, Integer> findIndex(List<List<String>> stringArr, String keyString) {
        List<String> flattenedArr = new ArrayList<>();
        for (List<String> row : stringArr) {
            flattenedArr.addAll(row);
        }
 
        int index = flattenedArr.indexOf(keyString);
        if (index != -1) {
            int rows = stringArr.size();
            int cols = stringArr.get(0).size();
            return new Tuple<>(index / cols, index % cols);
        }
 
        return new Tuple<>(-1, -1);
    }
 
    public static void main(String[] args) {
        List<List<String>> stringArr = new ArrayList<>();
        stringArr.add(new ArrayList<>(List.of("a", "h", "b")));
        stringArr.add(new ArrayList<>(List.of("c", "d", "e")));
        stringArr.add(new ArrayList<>(List.of("g", "t", "r")));
 
        String keyString = "e";
 
        Tuple<Integer, Integer> result = findIndex(stringArr, keyString);
 
        System.out.println("The indices are: " + result.x + ", " + result.y);
    }
}


Python3




# Python code
def findIndex(stringArr, keyString):
    flattenedArr = [item for sublist in stringArr for item in sublist]
    try:
        index = flattenedArr.index(keyString)
        rows = len(stringArr)
        cols = len(stringArr[0])
        return index // cols, index % cols
    except ValueError:
        return -1, -1
 
stringArr = [
    ["a", "h", "b"],
    ["c", "d", "e"],
    ["g", "t", "r"]
]
 
keyString = "e"
 
result = findIndex(stringArr, keyString)
 
print("The indices are:", result[0], ",", result[1])
 
# This code is contributed by Utkarsh Kumar


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    static Tuple<int, int> FindIndex(List<List<string>> stringArr, string keyString)
    {
        List<string> flattenedArr = new List<string>();
        foreach (var row in stringArr)
        {
            flattenedArr.AddRange(row);
        }
 
        int index = flattenedArr.FindIndex(x => x == keyString);
        if (index != -1)
        {
            int rows = stringArr.Count;
            int cols = stringArr[0].Count;
            return new Tuple<int, int>(index / cols, index % cols);
        }
 
        return new Tuple<int, int>(-1, -1);
    }
 
    static void Main(string[] args)
    {
        List<List<string>> stringArr = new List<List<string>>
        {
            new List<string> { "a", "h", "b" },
            new List<string> { "c", "d", "e" },
            new List<string> { "g", "t", "r" }
        };
 
        string keyString = "e";
 
        Tuple<int, int> result = FindIndex(stringArr, keyString);
 
        Console.WriteLine("The indices are: " + result.Item1 + ", " + result.Item2);
    }
}


Javascript




// Define a class named Tuple with two generic parameters X and Y.
class Tuple {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
 
// Define a function named findIndex that takes a 2D array (list of lists) and a key string as input.
function findIndex(stringArr, keyString) {
    // Flatten the 2D array into a single array.
    let flattenedArr = [];
    for (let row of stringArr) {
        flattenedArr = flattenedArr.concat(row);
    }
 
    // Find the index of the keyString in the flattened array.
    let index = flattenedArr.indexOf(keyString);
    if (index !== -1) {
        // If the keyString is found, calculate the row and column indices.
        let rows = stringArr.length;
        let cols = stringArr[0].length;
        return new Tuple(Math.floor(index / cols), index % cols);
    }
 
    // If the keyString is not found, return a Tuple with (-1, -1).
    return new Tuple(-1, -1);
}
 
// Define the main function.
function main() {
    // Create a 2D array (list of lists) named stringArr.
    let stringArr = [
        ["a", "h", "b"],
        ["c", "d", "e"],
        ["g", "t", "r"]
    ];
 
    // Define the keyString to search for.
    let keyString = "e";
 
    // Call the findIndex function to find the indices of keyString.
    let result = findIndex(stringArr, keyString);
 
    // Print the result.
    console.log("The indices are: " + result.x + ", " + result.y);
}
 
// Call the main function to start the program.
main();


Output

The indices are: 1, 2






Time Complexity: O(rows * cols)
Auxiliary Space: O(rows * cols)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads