You are given an array a consisting of n (n≥3) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array [4,11,4,4] all numbers except one are equal to 4 ).
Print the index of the element that does not equal others. The numbers in the array are numbered from one.
Input
The first line contains a single integer t (1≤t≤100). Then t test cases follow.
The first line of each test case contains a single integer n (3≤n≤100) — the length of the array a .
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤100).
It is guaranteed that all the numbers except one in the a array are the same.
Output
For each test case, output a single integer — the index of the element that is not equal to others.
In our approach, we assume that the first element of the array is tmp1. Then, in the first for loop, the program traverses the array and compares each current element with tmp1 to find the second distinct value tmp2 and records its position as tmp2Idx.
In the second for loop, the program traverses the array backward, starting from the end. In each iteration, it checks whether the current element is equal to tmp1. If it is, it means the current element is not the unique number because there exists another distinct number, whose position is tmp2Idx. Therefore, the program outputs tmp2Idx + 1, which represents the position of the second distinct element. If the current element is not equal to tmp1, it means the current element is the unique number because no other number is equal to it. Thus, the program outputs 1, indicating the position of the first element.
This approach ensures finding the position of the unique number in the array and requires only two traversals of the array, making it highly efficient. The time complexity of this solution is O(n).
C# Solution
Solution1
int t = int.Parse(Console.ReadLine());
for(int i=0; i<t; i++){
int n = int.Parse(Console.ReadLine());
int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
var tmp1 = arr[0];
var tmp2 = 0;
var tmp2Idx = 0;
for(int j=1; j<arr.Length; j++){
if(arr[j]!=tmp1){
tmp2 = arr[j];
tmp2Idx = j;
break;
}
}
for(int k=arr.Length-1; k>0; k--){
if(k!=tmp2Idx){
if(arr[k]==tmp1){
Console.WriteLine(tmp2Idx+1);
break;
}
else{
Console.WriteLine(1);
break;
}
}
}
}
Time Complexity : O(n)
Java Solution
Solution1
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine();
for(int i=0; i<t; i++){
int n = scanner.nextInt();
scanner.nextLine();
int[] arr = Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.toArray();
int tmp1 = arr[0];
int tmp2 = 0;
int tmp2Idx = 0;
for(int j=1; j<arr.length; j++){
if(arr[j]!=tmp1){
tmp2 = arr[j];
tmp2Idx = j;
break;
}
}
for(int k=arr.length-1; k>0; k--){
if(k!=tmp2Idx){
if(arr[k]==tmp1){
System.out.println(tmp2Idx+1);
break;
}
else{
System.out.println(1);
break;
}
}
}
}
}
}
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
tmp1 = arr[0]
tmp2 = 0
tmp2Idx = 0
for j in range(1,len(arr)):
if(arr[j]!=tmp1):
tmp2 = arr[j];
tmp2Idx = j;
break;
for k in range(len(arr)-1, 0, -1):
if(k!=tmp2Idx):
if(arr[k]==tmp1):
print(tmp2Idx+1)
break
else:
print(1)
break
Conclusion
🧡If my solution helps, that is my honor!
🧡You can support me by sharing my posts, thanks you~~
✅If you got any problem about the explanation or you need other programming language solution, please feel free to let me know !!
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"6740fd2c82"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"6740fd2c82","uagb_grid_ajax_nonce":"2503a26f73"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-613bccac .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderStyle":"none","overallBorderColor":"","block_id":"613bccac","categories":"269","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"orderBy":"rand","excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"imageRatio":"2-3","imgEqualHeight":true,"extended_widget_opts":{"id_base":-1,"column":{"desktop":"12","tablet":"12","mobile":"12"},"alignment":{"desktop":"default","tablet":"default","mobile":"default"},"roles":{"state":"","options":"hide"},"visibility":{"selected":"0","options":"hide","acf":{"visibility":"hide","field":"","condition":"","value":""}},"author_page":{"author_pages":{"selections":"1"}},"devices":{"options":"hide"},"days":{"options":"hide"},"dates":{"options":"hide","from":"","to":""},"styling":{"selected":"0","bg_image":"","background":"","background_hover":"","heading":"","text":"","links":"","links_hover":"","border_color":"","border_type":"","border_width":"","background_input":"","text_input":"","border_color_input":"","border_type_input":"","border_width_input":"","background_submit":"","background_submit_hover":"","text_submit":"","border_color_submit":"","border_type_submit":"","border_width_submit":"","list_border_color":"","table_border_color":""},"class":{"selected":"0","link":"","id":"","classes":"","animation":"","event":"enters","speed":"","offset":"","delay":"","logic":""},"tabselect":"0"},"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","inheritFromThemeBtn":false,"buttonType":"primary","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"align":"left","width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","useSeparateBoxShadows":true,"boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationMarkup":"","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false,"paginationType":"ajax","isLeftToRightLayout":false,"wrapperTopPadding":"","wrapperRightPadding":"","wrapperLeftPadding":"","wrapperBottomPadding":"","wrapperTopPaddingTablet":"","wrapperRightPaddingTablet":"","wrapperLeftPaddingTablet":"","wrapperBottomPaddingTablet":"","wrapperTopPaddingMobile":"","wrapperRightPaddingMobile":"","wrapperLeftPaddingMobile":"","wrapperBottomPaddingMobile":"","wrapperPaddingUnit":"px","wrapperPaddingUnitTablet":"px","wrapperPaddingUnitMobile":"px","wrapperPaddingLink":false,"wrapperAlign":"row","wrapperAlignPosition":"center","extended_widget_opts_block":{},"extended_widget_opts_state":"","extended_widget_opts_clientid":"","dateUpdated":""}, pageNumber, '613bccac');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};