📍 [ JAVA ] ✔ Faster than 100% ✔ Simple explanation 📢
Complexity:\nTime complexity: O(n)\nSpace complexity: O(1)\n\n\nclass Solution {\n    public int nearestValidPoint(int x, int y, int[][] points) {\n        \n  
**Complexity:**\n*Time complexity: O(n)\nSpace complexity: O(1)*\n\n```\nclass Solution {\n    public int nearestValidPoint(int x, int y, int[][] points) {\n        \n        int index = -1;\n        int closest = Integer.MAX_VALUE;\n        int[] point;\n        \n        for (int i = 0; i < points.length; i++) {\n            \n            point = points[i];\n             \n            if (point[0] == x || point[1] == y) {\n                \n                if (point[0] == x && point[1] == y) {\n                \n                    return i;\n                \n                }\n                \n                int dist = Math.abs(point[0] - x) + Math.abs(point[1] - y);\n                \n                if (dist < closest) {\n                    \n                    closest = dist;\n                    index = i;\n                    \n                }\n                \n            }\n            \n        }\n        \n        return index;\n        \n    }\n    \n}\n```\n\n**Explanation:**\nFor this problem we can think of it in two parts. The first part is finding whether or not one of the `X` or `Y` of any given point matches the `X` and `Y` parameters. The second part is calculating the *Manhattan Distance* of the two points and returning the the first index of the nearest point.\n\nWe want to iterate over every point in the `points` array and check if either `X` or `Y` value is matching. If not we will skip to the next item. Next, we can check if the point matches exactly the `X` and `Y` parameters, in which case we can return early. If not, we calculate the Manhattan Distance and check if it is smaller than but NOT EQUAL TO the current closest distance. We then return the index.\n\n**If this solution was helpful in any way I would greatly appreciate an upvote. For solutions to other problems, feel free to click on my account as I have many more solutions on many different problems.**
['Java']